c++ 在成员函数中用作参数时,前向声明不起作用

s4n0splo  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(121)

我在类A之前对class B;的前向声明在下面的代码中不起作用,即使this answer提到在函数的参数中使用不完整类型的前向声明时也应该起作用。
它在A::func()中抛出一个错误,说“未定义类型B”。对此应该如何修复?为什么我的前向声明在这种情况下不起作用?
代码

#include <iostream>
using namespace std;

class B;

class A
{
public:
    A()
    {
        cout << "in A's default ctor" << endl;
    }

    void func(B b1)
    {
        cout << "in A's func" << endl;
    }
private:
    int x;
};

class B
{
public:
    B()
    {
        cout << "in B's default ctor" << endl;
    }

    B(const B& b1)
    {
        cout << "in B's copy ctor" << endl;
    }

    B& operator=(const B& b1)
    {
        cout << "in B's copy assignment operator" << endl;
        return *this;
    }
    
};    

int main()
{
    A a;
    B b;

    a.func(b);
}

字符串

ars1skjm

ars1skjm1#

来自C++17标准(6.2单定义规则,第5页)
一个类类型T必须是完整的,如果
(5.9)- 返回类型或参数类型为T的函数被定义(6.1)或调用(8.2.2),或者
为了避免这个错误,在类B的定义之后,在类A之外定义成员函数func

class B;

class A
{
public:
    //...
    void func(B b1);
    //...
};

class B
{
    //...
};

void A::func(B b1)
{
    cout << "in A's func" << endl;
}

字符串
或者没有forward声明,

class A
{
public:
    //...
    void func(class B b1);
    //...
};

class B
{
    //...
};

void A::func(B b1)
{
    cout << "in A's func" << endl;
}

相关问题