使用 new 关键字进行前向声明和类型名
我在类 a 中声明类型 b 的新指针时遇到错误。请帮忙。
#include <iostream>
namespace B
{
class b;
}
class a
{
private:
B::b* obj_b;
public:
a(){}
~a(){}
void create()
{
b* obj_b = new b;
}
};
class b
{
private:
a *obj_a;
public:
b()
{
obj_a->create();
}
~b(){}
};
int main()
{
b obj;
return 0;
}
I'm getting an error below in the class a declaring a new pointer of type b. Please help.
#include <iostream>
namespace B
{
class b;
}
class a
{
private:
B::b* obj_b;
public:
a(){}
~a(){}
void create()
{
b* obj_b = new b;
}
};
class b
{
private:
a *obj_a;
public:
b()
{
obj_a->create();
}
~b(){}
};
int main()
{
b obj;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是你的问题。您可以声明一个指向 B 的指针,因为指针的大小都相同,但如果不向编译器提供类定义,则无法构造指针或按值获取指针。如何知道如何为未知类型分配内存?
And there is your problem. You can declare a pointer to a B because pointers are all the same size, but you cannot construct one or take one by value without providing the class definition to the compiler. How would it possible know how to allocate memory for an unknown type?
您的代码中有很多错误。这些与前向声明、完全限定名称使用等相关。
There were many errors in your code. These are related to forward declaration, fully qualified name usage etc.