【问题标题】:Problems with struct prototyping (Invalid use of undefined type) c++结构原型的问题(未定义类型的无效使用)c ++
【发布时间】:2013-10-10 08:48:39
【问题描述】:

我希望我的 caba 结构包含一个指向 aba 结构变量的指针。而且我还希望 aba 结构根据 set 的属性进行一些操作。

但是当我在 caba 中使用 aba 指针的属性时,我得到一个错误

#include<stdio.h>
#include<set>
using namespace std;
struct aba;
struct caba
{
    aba *m;
    int z;
    bool operator >(const caba &other)
    {
        if(m==NULL||other.m==NULL)
            return true;
        return (*m).x>(*(other.m)).x;
    }
};
set <caba> t;
struct aba
{
    int x,y;
    bool f()
    {
        return !t.empty();
    }
};

int main()
{
    return 0;
}

说:

在成员函数`bool caba::operator>(const caba&)'中:

Test.cpp|13|错误:无效使用未定义类型`struct aba'

Test.cpp|4|错误:`struct aba' 的前向声明

Test.cpp|13|错误:无效使用未定义类型`struct aba'

Test.cpp|4|错误:`struct aba' 的前向声明

但为什么 aba 未定义?它有一个原型。

【问题讨论】:

    标签: c++ pointers struct


    【解决方案1】:

    您已声明 aba,但您的代码也需要定义。您可以做的是将有问题的代码从 caba 类定义中移出到包含 aba.hcaba.h.cpp 实现文件中。

    // caba.h (include guards assumed)
    struct aba;
    struct caba
    {
        aba *m;
        int z;
        bool operator >(const caba &other);
    };
    
    //caba.cpp
    #include "caba.h"
    #include "aba.h"
    bool caba::operator >(const caba &other)
    {
        if(m==NULL||other.m==NULL)
            return true;
        return (*m).x>(*(other.m)).x;
    }
    

    【讨论】:

    • 谢谢。难道没有办法将两个类放在一个文件中吗?
    • 最好按照 juanchopanza 建议的方式进行,或者你可以试试这个ideone.com/Vw4Vcz
    • @user2136963 是的,有,但是你还是要把bool caba::operator&gt;的定义放在aba类定义之后。
    • @user2136963 或者只是在aba 的定义下移动operator&gt; 函数定义应该可以工作。
    猜你喜欢
    • 2019-03-15
    • 1970-01-01
    • 2019-09-07
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多