64,648
社区成员
发帖
与我相关
我的任务
分享
#pragma once
#ifndef X_H
#define X_H
#include"Y.h"
struct X
{
Y y;
Y* py = &y;
};
#endif // !X_H
#pragma once
#ifndef Y_H
#define Y_H
#include"X.h"
struct Y
{
X x;
};
#endif // !Y_H
#include"X.h"
#include"Y.h"
int main()
{
X xx;
Y yy;
}
#ifndef CP5_ex7_31_h
#define CP5_ex7_31_h
class Y;
class X {
Y* y = nullptr;
};
class Y {
X x;
};
#endif
为什么这个答案是正确的?[/quote]
不能计算大小的问题
X Y之中相互定义其对象,两边都依赖彼此的大小,导致根本计算不了
但是你第二个例子就不一样了
指针和引用所需要的存储大小是可计算的
一方使用 引用或者指针,就没有循环计算彼此大小的困扰[/quote]
X.h:
#pragma once
#ifndef X_H
#define X_H
#include"Y.h"
struct X
{
Y* py = nullptr;
};
#endif // !X_H
我把X类中的Y对象去掉了,用nullptr初始化指向Y的指针,还是不行,和刚才的报错一样... ...[/quote]
1L不是说了么,相互包含头文件,用前置声明替代
#ifndef CP5_ex7_31_h
#define CP5_ex7_31_h
class Y;
class X {
Y* y = nullptr;
};
class Y {
X x;
};
#endif
为什么这个答案是正确的?[/quote]
不能计算大小的问题
X Y之中相互定义其对象,两边都依赖彼此的大小,导致根本计算不了
但是你第二个例子就不一样了
指针和引用所需要的存储大小是可计算的
一方使用 引用或者指针,就没有循环计算彼此大小的困扰[/quote]
X.h:
#pragma once
#ifndef X_H
#define X_H
#include"Y.h"
struct X
{
Y* py = nullptr;
};
#endif // !X_H
我把X类中的Y对象去掉了,用nullptr初始化指向Y的指针,还是不行,和刚才的报错一样... ...
#ifndef CP5_ex7_31_h
#define CP5_ex7_31_h
class Y;
class X {
Y* y = nullptr;
};
class Y {
X x;
};
#endif
为什么这个答案是正确的?[/quote]
不能计算大小的问题
X Y之中相互定义其对象,两边都依赖彼此的大小,导致根本计算不了
但是你第二个例子就不一样了
指针和引用所需要的存储大小是可计算的
一方使用 引用或者指针,就没有循环计算彼此大小的困扰
#ifndef CP5_ex7_31_h
#define CP5_ex7_31_h
class Y;
class X {
Y* y = nullptr;
};
class Y {
X x;
};
#endif
为什么这个答案是正确的?