我是C++的新手,目前正在研究多态性。
我有这个代码:
#include <iostream>
class Base
{
public:
void say_hello()
{
std::cout << "I am the base object" << std::endl;
}
};
class Derived: public Base
{
public:
void say_hello()
{
std::cout << "I am the Derived object" << std::endl;
}
};
void greetings(Base& obj)
{
std::cout << "Hi there"<< std::endl;
obj.say_hello();
}
int main(int argCount, char *args[])
{
Base b;
b.say_hello();
Derived d;
d.say_hello();
greetings(b);
greetings(d);
return 0;
}
输出位置:
I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the base object
这并没有认识到问候语函数中的多态性。
如果我把virtual
关键字放在say_hello()
函数中,这看起来像预期的那样工作,并输出:
I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the Derived object
所以我的问题是:使用指针/引用时检索多态效果?
当我看到教程时,他们会展示这样的东西:
Base* ptr = new Derived();
greetings(*ptr);
我想知道在使用多态性时是否必须总是使用指针。
如果这个问题太基础,很抱歉。
对于多态行为,您需要两件事:
- 派生类中重写的虚拟方法
- 通过基类指针或引用对派生对象的访问
Base* ptr = new Derived();
这些都是糟糕的教程。永远不要使用拥有的原始指针和显式的new/delete。请改用智能指针。
只需向方法添加一个虚拟声明,就可以在使用对基类的引用时覆盖它:
virtual void say_hello() {...}
在两个类中(或者至少只有基类(。