首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于继承中的构造函数调用有关问题.

2012-02-16 
关于继承中的构造函数调用问题..代码如下:#includeiostream usingnamespacestdclassA{public:A(){cout

关于继承中的构造函数调用问题..
代码如下:

#include   "iostream "
using   namespace   std;
class   A
{
public:
A(){cout < < "this   A " < <endl;}
A(int   x,int   s){k=x;q=s;cout < < "this   is   a(int   x) " < <endl;}
private:
int   k;
int   q;
};
class   B:public   A
{
public:
        B(){cout < < "this   is   B " < <endl;}
        B(int   i,int   j):A(1,2)  
            {   aa=i;bb=j;  
                  cout < < "aa " < <aa < <endl < < "bb " < <bb < <endl;
              }
private:
int   aa;
int   bb;

};
main()
{
                  B   (2,3);

return   0;
}
按道理说,应该先调用基类的构造函数,输出 "this   is   A ",然后在输出 "this   is   a(int   x),最后是aa=..bb=..
但在机器上运行后得到:
this   is   a(int   x)
aa2
bb3

怎么最后运算确是这个结果?



[解决办法]
B (2,3)==>
B(int i,int j):A(1,2)
===> A(int x,int s){k=x;q=s;cout < < "this is a(int x) " < <endl;}

[解决办法]
楼主,你要看调用的是哪个构造函数,带参数的构造函数,B(int i,int j):A(1,2) ,这个就不会调用默认构造函数(无参构造函数)了
[解决办法]
同意楼上
如果你定义一个对象 B b;
则会先调用A(){cout < < "this A " < <endl;}然后 B(){cout < < "this is B " < <endl;}

热点排行