【问题标题】:c++ inheritance default constructor [closed]C++继承默认构造函数[关闭]
【发布时间】:2014-06-16 19:49:45
【问题描述】:

  class A{
       public:
           A(){ cout << “A ctor” << endl; }//default A constructor
           A(const A& a){ cout <<“A copy ctor”<< endl; }//copy constructor
           virtual ~A(){ cout <<“A dtor”<< endl; }//destructor
           virtual void foo(){ cout <<”A foo()” << endl; }
           virtual A& operator=(const A& rhs){ cout << “A op=” << endl; }//operator
    };

class B:public A{
   public:
       B(){ cout <<“B ctor”<< endl; }//default B constructor 
       virtual ~B(){ cout <<”B dtor”<< endl; }//destructor
       virtual void foo(){ cout <<”B foo()”<< endl; }
   protected:
       A mInstanceOfA;
}; 

A foo(A& input){
    input.foo();
    return input;
}


Int main(){
    B myB;
    B myOtherB;
    A myA;
    myOtherB=myB;
    myA=foo(myOtherB);
}

这个程序打印:

A ctor
A ctor
B ctor
A ctor
A ctor
B ctor
A ctor
A op=
A op=
B foo()
A copy ctor
A op=
A dctor

为什么在打印“B ctor”之前打印 2 次“A ctor” 以及为什么要在程序“A copy ctor”、“A op="、“A dctor”的末尾打印??*/

【问题讨论】:

  • blink 标签到底在里面做什么?在主题上,这个程序不能编译,更不用说打印任何东西了。但看起来book 很容易回答。

标签: c++ inheritance default


【解决方案1】:

它在 B 之前打印 A 两次,因为:

  1. 第一次是因为B派生自A,所以是基类的实例化
  2. 第二次是因为B 包含 A 的一个实例作为成员变量。所以在 B 的构造函数被调用之前,它也会被实例化。

最后,打印出 A 的复制构造函数、赋值操作和析构函数,因为 foo() 按值返回 A 的实例,因此需要将其复制到其目的地。

此外,您可能希望更好地格式化并提出您的问题,否则有人会否决它们。

【讨论】:

    猜你喜欢
    • 2015-07-09
    • 2016-03-24
    • 2013-10-24
    • 2017-10-04
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多