先了解一下环境:
#include<iostream>
class B;
class A {
B* temp;
void printf() {
std::cout << temp->b << std::endl;
}
};
class B {
int b;
A* temp;
};
int main() {
}
这种情况我们虽然用了类的前置声明,但是因为在A先于B编译,所以编译A时,A并不知道有B的存在,也不知道B占用的空间大小,这是编译器不允许的,编译一定要知道一个变量的大小才能进行正常的编译,所以当编译到输出行时调用了B中的b成员,但编译器不知道b是int型也就不能给b分配空间,自然就报错了;
这个时候我们可以用模板类来解决这一问题:
#include<iostream>
class B;
template<class T>
class A {
public:
T* temp;
A() {
temp = new T();
temp->b = 1;
}
void printf() {
std::cout << temp->b << std::endl;
}
};
class B {
public:
int b;
A<B>* temp;
};
int main() {
A<B> a;
a.printf();
}
我们在编译main函数时才给A分配空间