gpt4 book ai didi

c++ - 不完整类型错误,使用友元函数时

转载 作者:太空狗 更新时间:2023-10-29 21:06:33 27 4
gpt4 key购买 nike

#include <stdio.h>
class B;

class A;

class A
{
int a;
friend int B::f();
};


class B
{
int b;
class A x;
public:
int f();
};

int B::f()
{
// ...
}

main()
{
class B b;
b.f();
}

错误:

a.cpp:9: error: invalid use of incomplete type ‘struct B’

a.cpp:2: error: forward declaration of ‘struct B’

这个问题不能通过将 B 的定义放在 A 之前来解决B 有一个 A 类型的对象。

对于这个例子,让 B 成为友元类就可以了,但是在我的真实代码我在 B 中有更多成员函数(所以我需要替代解决方案)。

最后,有人可以给我链接来解释编译器出现时的作用吗跨越前向声明、声明、定义。

最佳答案

你根本无法按原样做你想做的事。要在类 A 中声明友元函数,需要在定义类 A 之前了解类 B 的性质。要使类 B 包含类 A 的实例,必须在定义类 B< 之前知道类 A 的性质。第 22 条军规。

如果您使类 B 成为类 A 的 friend 类,则前者不适用。如果您修改 B 以包含指向类 A 的实例的指针或引用,则后者不适用。

关于c++ - 不完整类型错误,使用友元函数时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7461274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com