简体   繁体   English

C ++继承和多态

[英]C++ inheritance and polymorphism

Being a Java Programmer and a C++ noob, I'm having a tough time dealing with inheritance in C++. 作为Java程序员和C ++ noob,我在处理C ++中的继承时遇到了困难。 Right now, I have this: 现在,我有这个:

class Parent {
public:
    Parent() {}
    virtual std::string overrideThis() { }
};

class Child : public Parent {
public:
    std::string attribute;
    Child(const std::string& attribute) : attribute(attribute) { }
    std::string overrideThis(){
    std::cout << "I'm in the child" << std::endl;
    return attribute.substr(1, attribute.size()-2);
    }
};

And this snippet somewhere else: 而这个片段在其他地方:

Child *child = new Child(value);
Child childObject = *(child);
std::cout << "I'm trying this: " << childObject.overrideThis() << endl;

The code above works as expected a the message is printed on screen. 上面的代码按预期工作,消息打印在屏幕上。 But if instead of that I try this: 但如果不是我试试这个:

Child *child = new Child(value);
Parent childObject = *(child);
std::cout << "I'm trying this: " << childObject.overrideThis() << endl;

I have a funny runtime error with lots of funny characters on my Screen. 我有一个有趣的运行时错误,屏幕上有很多有趣的人物。 What's the proper way of using polymorphism with pointers? 将多态与指针一起使用的正确方法是什么? What I'm trying to do is invoke overrideThis() on a Child instance 我要做的是在Child实例上调用overrideThis()

The program has undefined behavior because the function that is being called - Parent::overrideThis doesn't return, although it should. 该程序具有未定义的行为,因为正在调用的函数 - Parent::overrideThis不会返回,尽管它应该返回。

The function in the Parent class is called because Parent childObject = *(child); 调用Parent类中的函数,因为Parent childObject = *(child); slices the object the you attempt to copy - the new object, childObject is of type Parent , not Child . 切片您尝试复制的对象 - 新对象, childObject的类型为Parent ,而不是Child

For polymorphism to work, you need to use either pointers or references: 要使多态性起作用,您需要使用指针或引用:

Parent* childObject1 = child;
Parent& childObject2 = *child;
childObject1->overrideThis();
childObject2.overrideThis();

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

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