2

我在下面运行程序,在 main 的第一行之后我得到了这个输出:

1
6
1
6
13

谁能解释为什么它两次进入Grandand的构造函数?Father

//base class 
class Grand{
public:
    Grand(){cout<<"1"<<endl;}
    Grand(const Grand & g){cout<<"2"<<endl;}
    virtual ~Grand  (){cout<<"3"<<endl;}
    virtual void fun1(Grand g){cout<<"4"<<endl;}
    virtual void fun3(){cout<<"5"<<endl;}
private:
    int m_x;
    };



//derived class 
    class Father: public Grand{
    public:
        Father(){cout<<"6"<<endl;}
        Father(const Father & f){cout<<"7"<<endl;}
        ~Father(){cout<<"8"<<endl;}
        void fun1(){cout<<"9"<<endl;}
        void fun2(Father & f){
            cout<<"10";
            f.fun3();
        }
        void fun3(){
            cout<<"11"<<endl;
        }
        virtual void fun4(){
            cout<<"12"<<endl;
        }
    };


sing namespace std;

//derived class 
        class Son: public Father{
        public:
            Son(){cout<<"13"<<endl;}
            Son(const Son& s){cout<<"14"<<endl;}
            ~Son(){cout<<"15"<<endl;}
            void fun3(){cout<<"16"<<endl;}
            virtual void fun5(Son& s){
                cout<<"17"<<endl;
                s.fun1();
            }
        private:
            Father m_f;
            };

int main(){
Grand * pGrand= new Son; 
.........
.........
}
4

1 回答 1

9

因为你都从父亲继承并实例化了一个父亲类型的成员,所以现在 Son 有两个父亲对象——直接基类和一个成员。

于 2013-01-08T10:42:42.590 回答