还是初级老问题 某类中嵌套一个小类 小类中设计的指向大类对象的指针赋值错误 高手进来看看

niuwei0 2009-03-28 12:24:33
#include <iostream>
using namespace std;

class Small
{
public:
int b;
void* pMyBig;
public:
Small(int x,void* pBig):b(x),pMyBig(pBig){}
};

class Big
{
public:
int a;
Small MySmall;
public:
Big(int y,int z,void* pBig):a(y),MySmall(z,pBig){}
};

void main()
{
Big MyBig(1,2,NULL);
(Big*)MyBig.MySmall.pMyBig = &MyBig;//错误1所在行
cout<<MyBig.MySmall.pMyBig->a<<endl;//错误2所在行
}

结果错误 错误提示:
错误1 error C2106: '=' : left operand must be l-value
错误2 rror C2227: left of '->a' must point to class/struct/union

我的想法是内嵌的Small中设计了void型指针 是因为如果我设置了Big*指针 Big要在Small之前定义 而Big中又包含Small 只能向前声明 比较麻烦
我想先设计void* 然后Big的对象MyBig构造成功后 再把void*强制转换成Big* 然后把&MyBig赋值给pMyBig 这样pMyBig就成功指向外层这个大类的对象了

哪里有问题呢 高手帮帮我
...全文
106 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
mengde007 2009-03-28
  • 打赏
  • 举报
回复
这种问题还没听说过,MyBig.MySmall.pMyBig是一个空类型指针,而MyBig是一个类对象,
MyBig.MySmall.pMyBig哪来的空间可以装一个类?如果说pMyBig和MyBig都是一个普通的指针,那还可以转化试试,
zhangjundriver 2009-03-28
  • 打赏
  • 举报
回复
没有看懂你的意图。想学学都不行啊。
muyejingfeng100 2009-03-28
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;

class Small
{
public:
int b;
void* pMyBig;
public:
Small(int x,void* pBig):b(x),pMyBig(pBig){}
};

class Big
{
public:
int a;
Small MySmall;
public:
Big(int y,int z,void* pBig):a(y),MySmall(z,pBig){}
};

void main()
{
Big MyBig(1,2,NULL);
MyBig.MySmall.pMyBig = &MyBig;//错误1所在行
Big *p = (Big*)MyBig.MySmall.pMyBig;//
//cout <<MyBig.MySmall.pMyBig->a <<endl;//错误2所在行
cout<<p->a<<endl;
}
downmooner 2009-03-28
  • 打赏
  • 举报
回复
void main()
{
Big MyBig(1,2,NULL);
MyBig.MySmall.pMyBig = (void*)(&MyBig);//错误1所在行
cout <<((Big*)MyBig.MySmall.pMyBig)->a <<endl;//错误2所在行
}
whhvc 2009-03-28
  • 打赏
  • 举报
回复
5楼验证 是正确的
niuwei0 2009-03-28
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 mengde007 的回复:]
这种问题还没听说过,MyBig.MySmall.pMyBig是一个空类型指针,而MyBig是一个类对象,
MyBig.MySmall.pMyBig哪来的空间可以装一个类?如果说pMyBig和MyBig都是一个普通的指针,那还可以转化试试,
[/Quote]

我赋值的是&MyBig啊 不是MyBig
sdljgxb 2009-03-28
  • 打赏
  • 举报
回复
学习~
  • 打赏
  • 举报
回复

class Small
{
public:
int b;
void* pMyBig;
public:
Small(int x,void* pBig):b(x),pMyBig(pBig){}
};

class Big
{
public:
int a;
Small MySmall;
public:
Big(int y,int z,void* pBig):a(y),MySmall(z,pBig){}
};

void main()
{
Big MyBig(1,2,NULL);
MyBig.MySmall.pMyBig = &MyBig;//错误1所在行 //左值别转了,右边会隐式子转换的
cout << ((Big*)MyBig.MySmall.pMyBig)->a <<endl;//错误2所在行 // 这里转换一下就可以了。
}

65,211

社区成员

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

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