简体   繁体   English

以基本实例为参数的派生类的构造方法

[英]Constructor of derived class with base instance as parameter

I have this code: 我有以下代码:

#include <stdio.h>

class A
{
public:
    A() { printf("A::A()\n"); }
    A(const A &a) { printf("A::A(A &a)\n"); }
    A &operator=(const A &a) { printf("A::operator=\n"); }
};

class B : public A
{
public:
    B() { printf("B:B()\n"); }
    B(const A &a) : A(a) { printf("B::B(A &a)\n"); }
    B &operator=(const B &b) { printf("B::operator=\n"); }
};

int
main(int argc, char *argv[])
{
    printf(">> B b1\n");
    B b1;
    printf(">> b2 = b1\n");
    B b2 = b1;
    return 0;
}

Why the line B b2 = b1 does not call the constructor B::B(const A &a) and instead calls A::A(const A &a) ? 为什么行B b2 = b1不调用构造函数B::B(const A &a)而是调用A::A(const A &a) How can I tell the compiler to do so? 如何告诉编译器这样做?

Because it calls B::B(const B &a) which in turn calls A::A(const A &a). 因为它调用B :: B(const B&a),然后又调用A :: A(const A&a)。 And you missed B::B(const B &a) in your class so you can't see it. 而且您在课堂上错过了B :: B(const B&a),所以您看不到它。

That is because: 那是因为:

This: 这个:

B(const A &a)  
{ 
    printf("B::B(A &a)\n"); 
}

is not a copy constructor! 不是副本构造函数!

However, this: 但是,这:

B(const B &a)  
{ 
    printf("B::B(A &a)\n"); 
}

is a copy constructor. 是副本构造函数。

With your version of copy constructor, you are ruining stack as well. 使用复制构造函数的版本,您也会破坏堆栈。

To prove you my point about stack corruption, you have got to try this: 为了证明我关于堆栈损坏的观点,您必须尝试以下操作:

Notice that it will never print "Inside B::Print()" 请注意,它将永远不会打印“ Inside B :: Print()”

class A
{
public:
    A() { printf("A::A()\n"); }
    A(const A &a) 
    { 
        printf("A::A(A &a)\n"); 
    }
    A &operator=(const A &a) { printf("A::operator=\n"); }
    void print(){printf("Inside A::Print()\n"); }
};

class B : public A
{
public:
    B() { printf("B:B()\n"); }
    B(const A &a)  
    { 
        printf("B::B(A &a)\n"); 
    }
    B &operator=(const B &b) { printf("B::operator=\n"); }

    void print(){printf("Inside B::Print()\n");}
};

int main(int argc, char *argv[])
{
    printf(">> B b1\n");
    B b1;
    b1.print();
    printf(">> b2 = b1\n");
    B b2 = b1;
    b2.print();
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM