使用不同的类初始化对象

时间:2017-01-09 12:48:22

标签: c++ oop inheritance initialization

我看到了这个例子: http://www.cplusplus.com/doc/tutorial/typecasting/#dynamic_cast

(...)
class Base { virtual void dummy() {} };
class Derived: public Base { int a; };
(...)
Base * pba = new Derived;
Base * pbb = new Base;
(...)

为什么'pba'是一个Base对象,如果用Derived初始化它?为什么不把它变成Derived对象?

Derived * pba = new Derived; // use this instead

它只是一个C ++的东西吗?

1 个答案:

答案 0 :(得分:1)

pbapbb都不是一个对象,但它们是基类Base类型的指针,所以在你的代码中你使用多指针指针,这意味着一个基指针可以指向同一个class或其派生类对象。

  • 使用new而不是pbb或pba创建对象,请考虑以下示例:

    #include <string>
    #include <iostream>
    using namespace std;
    
    
    class Base
    {
        public:
            virtual void Print() const { cout << "Base print()" << endl;} // virtual function
            void Greet()const {cout << "in Base Say: hello!" << endl;}
    };
    
    class Derived : public Base
    {
        public:
            void Print() const { cout << "Derived print()" << endl;} // ovrode the base member pritn()
            void Greet()const {cout << "in Derived Say: hello!" << endl;}
    };
    
    int main()
    {
    
        Base* pba = new Derived;
    
        pba->Print(); // Derived print()
        pba->Greet(); // in Base Say: hello! ??? because Greet() is not virtual
    
        Base* pbb = new Base;
    
        pbb->Print(); // Base print()
        pbb->Greet(); // in Base Say: hello!
    
        return 0;
    }
    

    因此在运行时,指针pba和pbb可以被赋予Base或Derived类的对象,因此相应地调用虚拟成员函数。