incomplete type is not allowed

killgxlin 2008-01-07 09:18:10
该如何解决?

class Car;
class Apple;

class Apple{
Car aCar;
}
};

class Car{
Apple anApple;
};

int main(){

return 0;
}
...全文
4964 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
killgxlin 2008-01-08
  • 打赏
  • 举报
回复

icl: NOTE: The evaluation period for this product ends on 24-jan-2008 UTC.
examp.cpp
examp.cpp(7): error: pointer to incomplete class type is not allowed
aCar->bcd();
^

compilation aborted for examp.cpp (code 2)
Wolf0403 2008-01-08
  • 打赏
  • 举报
回复
最后这个代码有什么问题?
killgxlin 2008-01-08
  • 打赏
  • 举报
回复
上面的代码有问题,应该是下面这个

class Car;
class Apple;

class Apple{
public:
void abc(Car *aCar){
aCar->bcd();
}
};

class Car{
public:
Apple anApple;
void bcd(){ }
};

int main(){
Apple app;
Car car;
app.abc(&car);
return 0;
}
killgxlin 2008-01-08
  • 打赏
  • 举报
回复
其实道理我明白,但是如果代码变成这个,又该怎么办呢?

class Car;
class Apple;

class Apple{
Car *aCar;
void abc(){
aCar->bcd();
}
}
};

class Car{
Apple anApple;
void bcd(){ }
};

int main(){

return 0;
}
killgxlin 2008-01-08
  • 打赏
  • 举报
回复
怎么结贴啊?
killgxlin 2008-01-08
  • 打赏
  • 举报
回复
嘿嘿,怎么给分啊?
ryfdizuo 2008-01-08
  • 打赏
  • 举报
回复

//指针的好处就是推迟实现嘛...
#include<iostream>
using namespace std;

class Car;
class Apple;

class Apple
{
public:
void abc(Car *aCar);
};

class Car
{
public:
Apple anApple;
void bcd(){ cout<<"The car is excuted!"<<endl;}
};

void Apple::abc(Car *aCar) //将aCar的调用放到car类的定义之后;
{
aCar->bcd();
}

int main()
{
Apple app;
Car car;
app.abc(&car);
return 0;
}
hastings 2008-01-08
  • 打赏
  • 举报
回复
class Car;
class Apple
{
Car *aCar;
public:
void abc();//须定义在外面
};
class Car
{
Apple anApple;
public:
void bcd()
{
cout<<"Car::bcd()\n";
}
};
void Apple::abc()
{
cout<<"Apple::abc()\n";
aCar->bcd();
}
int main()
{
Apple a;
a.abc();
////////////////////////////////////////////////////////
system("PAUSE");
return 0;
}
hastings 2008-01-07
  • 打赏
  • 举报
回复
楼主设想,Car原本大小为1字节,Apple原本大小也为1字节;
然后,互相无限包含,这个类的大小到最后会是多少???
用指针就不一样了。
ryfdizuo 2008-01-07
  • 打赏
  • 举报
回复

你的程序就是典型的”你中有我,我中有你“
1楼正解啊;肯定要用指针的, 只有这样才能推迟对象的定义的啊;
killgxlin 2008-01-07
  • 打赏
  • 举报
回复
嵌套定义,呵呵,同样的问题在我的程序中出现,但是他太长了,我把它简化出来放到这里。
ryfdizuo 2008-01-07
  • 打赏
  • 举报
回复
lz什么意思?你中有我,我中有你吗?
你这样为了实现什么?
^_^
killgxlin 2008-01-07
  • 打赏
  • 举报
回复
不好意思,不可以用指针解决:-)
Fioman 2008-01-07
  • 打赏
  • 举报
回复
Car aCar;
这样写在定义时编译器就需要知道Car占多少字节,而Car还没有定义;
而指针所占的字节是都是一定的,编译器可以知道为aCar分配多少字节。
Fioman 2008-01-07
  • 打赏
  • 举报
回复
换成指针


class Car;
class Apple;

class Apple{
Car* aCar;
};

class Car{
Apple* anApple;
};

int main(){

return 0;
}

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧