从继承类打印

时间:2017-09-11 04:27:48

标签: c++ c++11 inheritance polymorphism abstract-class

说我有这个代码,我想知道主要代码会打印什么。输出。起初我以为当调用第一个命令时,将调用Base的默认构造函数,然后打印“from Base”,然后调用A的构造函数,然后打印“from A”。 但我不确定因为我认为有可能因为当我们执行这个命令时,“Base * base = new A()”,我怀疑切片可能会发生,所以我希望你对打印输出有所帮助。

最后当我删除base时,那个打印应该按照我的想法排序: 它只会调用Base的析构函数和“from Base”。 所以因为在main中我们从派生类中添加一个new到基类,我不确定。 谢谢。

class Base {
    virtual void method() {
         std::cout << "from Base" << std::endl;
    }

public:
    virtual ~Base() {
         method();
    }
    void baseMethod() {
         method();
    }
}

class A: public Base {
    void method() {
        std::cout << "from A" << std::endl;
    }
public:
    ~A () { method();}
};


int main (void) {
    Base* base = new A();
    base -> baseMethod();
    delete base;
}

1 个答案:

答案 0 :(得分:0)

从稍微修改过的代码版开始,然后逐步完成。

它应该可以帮助您了解它是如何工作的。

#include <iostream>

class Base {

// since we're going to call this from the derived class's method(), it must at least be protected    
protected:
    virtual void method() {
         std::cout << "from Base" << std::endl;
    }

public:
    virtual ~Base() {
        std::cout << "calling ~Base()\n";
        // calling a virtual method from a base class constructor or destructor may not give you the result you expect.
        // at this point, the derived class is gone. the standard says that you will actually call Base::method, not A::method
         method();
    }
    void baseMethod() {
         method();
    }
};

class A: public Base {
    void method() {
        std::cout << "from A" << std::endl;
        Base::method();
    }
public:
    ~A () {
        std::cout << "calling ~A()\n";
        method();
        }
};


int main (void) {
    Base* base = new A();
    base -> baseMethod();
    delete base;
}

预期产出:

from A
from Base
calling ~A()
from A
from Base
calling ~Base()
from Base