C++编程技巧:使用模板类解决相互调用问题

先了解一下环境:

#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分配空间

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值