为该实例创建哪个类,并且此代码中的派生类在做什么?

问题描述 投票:0回答:2

此代码中的派生类在做什么,例如:

class Base
{
public:
       virtual std::string Name(){ return "Base Class"}

};
class Derived : public Base
{
 public:
        std::string Name() {return "Derived Class"}
}

int main()
{
   Base* object = new Derived();
   return 0;
}

我正在学习教程,但不理解上述代码中Base类的实例化中的Derived类在做什么。

c++ inheritance polymorphism instantiation
2个回答
1
投票

目标是实现polymorphism,这是一个OOP概念,除其他事项外,它使您可以使派生类方法重写基类。

请考虑以下内容:

class Base {
public:
    //virtual keyword allows method to be overriden
    virtual std::string Name() { return "Base Class"; }
    //virtual destructor needed for polymorphism otherwise it can lead to undefined behavior
    virtual ~Base(){} 
};

class Derived : public Base {
public:
    //optional keyword override signal the method has been overriden
    std::string Name() override { return "Derived Class"; }
};

class Derived2 : public Base {
public:
    std::string Name() override { return "Derived Class 2"; }
};

int main() {

    Base *object = new Derived();
    Base *object2 = new Derived2();
    Base *object3 = new Base();
    //collection of objects of type Base* which can hold any class of the family
    Base *collection[] = {object, object2, object3};

    for (auto &obj : collection) {//test print
        std::cout << obj->Name() << std::endl;
    }
}

正如评论所解释的,我可以拥有同一族的不同对象的集合,当您调用Name()时,方法调用将依赖于该对象。

输出:

Derived Class
Derived Class 2
Base Class

0
投票

main修改为:

int main()
{
   Base* object = new Derived();

   std::cout << object->Name() << std::endl;
   return 0;
}

并添加3个缺失的';'在您的代码中,您会看到写入Derived Class,被调用的方法NameDerivedobject的真实类型之一。

注意,名称基本中是虚拟,即使您没有明确说出,它也在派生中。

virtual允许在应用方法时使用对象的real类型,因此,当Namevirtual]时,甚至将object声明为Base。 >被调用的版本是Derived的真实类型之一


但是如果在Base

BaseName的定义中删除virtual,因为object被声明为Base,则被调用的方法是上定义的[Name。结果与在[[Derived上添加virtual是相同的,但仍在Base上将其删除,因为对于编译器

object

被声明为BaseName] >在Base上不是虚拟的,而没有考虑object的真实类型
© www.soinside.com 2019 - 2024. All rights reserved.