返回信息流#include <iostream>
using std::cout;
using std::endl;
//forward declaration
class B;
class A {
public:
A(B& ref)
:binA(ref)
{
cout << "A construct" << endl;
}
//data member
B& binA;
};
class B {
public:
B(A& ref)
:ainB(ref)
{
cout << "B consturct" << endl;
}
//data member
A& ainB;
};
class AandB {
public:
AandB()
:a(b),b(a)
{
cout << "AandB construct" << endl;
}
//data member
A a;
B b;
};
int main()
{
AandB aandb;
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #31146同步于 2009/11/11
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
两个类相互包含对方的引用为什么不会出错呢?
disk
2009/11/11镜像同步11 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
【 在 disk 的大作中提到: 】
: #include <iostream>
: using std::cout;
: using std::endl;
: ...................
为什么要出错呢?引用本身也是用指针来实现的,既然是用指针实现,那引用的大小也是确定的,既然大小确定了,那自然就没问题了
为啥今年帖子都是这样用
using std::endl;
using std::string;
using std::cout;
今年的老师是保护环境主义者,还是蛋疼?
[em21]
【 在 ericyosho 的大作中提到: 】
: 为啥今年帖子都是这样用
: using std::endl;
: using std::string;
: ...................
。。。。。。。。。
我一向是
void foo()
{
usi....
}
哈哈
【 在 ericyosho (ericyosho) 的大作中提到: 】
: 为啥今年帖子都是这样用
: using std::endl;
: using std::string;
: ...................
这段代码能执行吗?AandB的初始化列表里的b和a都分别还没初始化
怎么能相互赋值?不然A(&b)里的b应该是个空值吧 引用是不能为空的啊
没执行过,不知道运算结果怎样 但看着应该是不能执行的
【 在 disk 的大作中提到: 】
: #include <iostream>
: using std::cout;
: using std::endl;
: ...................
【 在 kulang25 的大作中提到: 】
: 这段代码能执行吗?AandB的初始化列表里的b和a都分别还没初始化
: 怎么能相互赋值?不然A(&b)里的b应该是个空值吧 引用是不能为空的啊
: 没执行过,不知道运算结果怎样 但看着应该是不能执行的
a和b的地址都已经有了,这就够了~
p.s.别看成引用,当成指针 = =
A(B& ref) ---> A构造函数需要一个B的地址
B(A& ref) ---> B的构造函数需要一个A的地址
【 在 ericyosho 的大作中提到: 】
: 为啥今年帖子都是这样用
: using std::endl;
: using std::string;
: ...................
某本书上写的吧, 这样很好啊, std名称空间里有很多常用的标识符 比如什么sort, swap, 一般都是些模板函数, 直接using 整个名称空间, 容易发生调用错误, 导致一些莫名奇妙的问题
今年?我三年前的时候看了一本叫C++ how to program的书是这么写的,之后就一直这么写了,不过也不知道有没好处。
【 在 ericyosho 的大作中提到: 】
: 为啥今年帖子都是这样用
: using std::endl;
: using std::string;
: ...................