返回信息流突然间有这样一个想法:有一个父亲,有一个儿子,儿子必须继承父亲,然后父亲有一个属性就是他的儿子(来指明他的儿子是谁),儿子有一个属性就是父亲(来指明它的父亲是谁),并且儿子一出生就应该有了父亲属性,假设父亲一出生也有了儿子属性。代码实现这两个类。
如果不用除了构造函数以外的方法,能不能实现之?
于是我动手写了下:
class Father
{
static int count = 0;
Son son;
//第二种,编译通过,运行出错
public Father()
{
this.son =new Son(this);
count++;
}
}
class Son extends Father
{
static int count = 0;
Father father;
public Son(Father father)
{
this.father = father;
count++;
}
}
class Demo
{
public static void main (String args[])
{
//Father father =new Father(new son(this);//no
//Son son = new Son(new Father()); //yes
//System.out.println(Father.count+Son.count);
Father father = new Father();
Son son = new Son(father);
System.out.println(Father.count+Son.count);
System.out.println(Father.count);
}
}
代码编译通过了,然后运行。。。不知道是什么情况,这是陷入了构造死循环了?
这是一条镜像帖。来源:北邮人论坛 / cpp / #77862同步于 2014/3/27
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[讨论]都是对象惹的祸!
shan10211865
2014/3/27镜像同步7 回复
订阅后,新回复会通过你的通知中心匿名送达。
7 条回复
用重载构造函数解决了,是溢出了,好像是堆溢出?。
【 在 sigmund 的大作中提到: 】
: 单步跟一下看,应该会导致栈溢出。
发自「贵邮」
嗯,都是面向对象,差不多。。。
子类构造函数会默认调用无参的父类构造函数,除非super指定
【 在 zx723 的大作中提到: 】
: 这不是java吗?哪死循环了。。。
发自「贵邮」
【 在 shan10211865 的大作中提到: 】
: 嗯,都是面向对象,差不多。。。
: 子类构造函数会默认调用无参的父类构造函数,除非super指定
: 发自「贵邮」
看起来是这个样子的