清华出版的钱能主编的C++程序设计教程P386页在介绍多继承时有一个程序,中间有一行我不明白,现向大家请教,代码如下:
#include <iostream.h>class Furniture
{public:
Furniture(){}
void SetWeight(int i){weight=i;}
int GetWeight(){returen weight;]
protected:
int weight;
};
class Bed:virtual public Furniture
{public:
bed(){}
void sleep(){cout<<"sleeping\n";}
};
class Sofa:virual public Furniture
{public:
sofa(){}
void WatchTV(){ cout<<"Watching TV\n";}
};
class SleeperSofa :public Bed,public Sofa
{public:
SleeperSofa():sofa(),Bed(){}//问题:此处为什么要写():sofa(),Bed(),没有什么参数要初始化呀,如果说因为继承所以要初始化的话那么sofa(){}和Bed(){}两个构造函数为什么不写成有初始化如果Bed():Furniture(){}的形式呢?
voidFoldOut(){ cout<<"Fold out the sofa\n":}
};
void main()
{ sleepersofa ss;
ss.SetWeight920);
cout<<ss.GetWeight()<<endl;
}
#include <iostream.h>class Furniture
{public:
Furniture(){}
void SetWeight(int i){weight=i;}
int GetWeight(){returen weight;]
protected:
int weight;
};
class Bed:virtual public Furniture
{public:
bed(){}
void sleep(){cout<<"sleeping\n";}
};
class Sofa:virual public Furniture
{public:
sofa(){}
void WatchTV(){ cout<<"Watching TV\n";}
};
class SleeperSofa :public Bed,public Sofa
{public:
SleeperSofa():sofa(),Bed(){}//问题:此处为什么要写():sofa(),Bed(),没有什么参数要初始化呀,如果说因为继承所以要初始化的话那么sofa(){}和Bed(){}两个构造函数为什么不写成有初始化如果Bed():Furniture(){}的形式呢?
voidFoldOut(){ cout<<"Fold out the sofa\n":}
};
void main()
{ sleepersofa ss;
ss.SetWeight920);
cout<<ss.GetWeight()<<endl;
}
其实钱老师这么写应该是为了增强继承的结构性
即为了读者明白在子类SleeperSofa 被构造的同时两个基类也是同时被构造一次的
从而产生了一个对象。这段代码中这些空的构造函数本身并没有起到什么作用
其实钱老师这么写应该是为了增强继承的结构性
即为了读者明白在子类SleeperSofa 被构造的同时两个基类也是同时被构造一次的
从而产生了一个对象。这段代码中这些空的构造函数本身并没有起到什么作用
按这个说法,不要sofa(),Bed()也可以了?
class SleeperSofa :public Bed,public Sofa
{public:
SleeperSofa():sofa(),Bed(){}
voidFoldOut(){ cout<<"Fold out the sofa\n":}
sofa rb;
};
现在的sofa有默认构造函数(不要参数的),
再问SleeperSofa():sofa(),Bed(){}中可以省略():sofa(),Bed()吗?
Bed():Furniture(){}在编译中会出错的。子类不能够显示的调用父类的构造函数。这个是由系统自动隐式调用的。class SleeperSofa :public Bed,public Sofa
{public:
SleeperSofa():sofa(),Bed(){}//问题:此处为什么要写():sofa(),Bed(),没有什么参数要初始化呀,如果说因为继承所以要初始化的话那么sofa(){}和Bed(){}两个构造函数为什么不写成有初始化如果Bed():Furniture(){}的形式呢?
voidFoldOut(){ cout<<"Fold out the sofa\n":}
};子类不能够显示的调用父类的构造函数。这个是由系统自动隐式调用的。可这里子类调用了父类的构造函数