我有一个小程序来演示简单的继承。我正在定义一个派生自 Mammal 的 Dog 类。这两个类共享一个名为 ToString() 的简单成员函数。当我不使用 virtual 关键字时,Dog 如何覆盖 Mammal 类中的实现? (我什至需要使用 virtual 关键字来覆盖成员函数吗?)
哺乳动物.h
#ifndef MAMMAL_H_INCLUDED
#define MAMMAL_H_INCLUDED
#include <string>
class Mammal
{
public:
std::string ToString();
};
#endif // MAMMAL_H_INCLUDED
哺乳动物.cpp
#include <string>
#include "mammal.h"
std::string Mammal::ToString()
{
return "I am a Mammal!";
}
狗.h
#ifndef DOG_H_INCLUDED
#define DOG_H_INCLUDED
#include <string>
#include "mammal.h"
class Dog : public Mammal
{
public:
std::string ToString();
};
#endif // DOG_H_INCLUDED
狗.cpp
#include <string>
#include "dog.h"
std::string Dog::ToString()
{
return "I am a Dog!";
}
主要.cpp
#include <iostream>
#include "dog.h"
using namespace std;
int main()
{
Dog d;
std::cout << d.ToString() << std::endl;
return 0;
}
输出
I am a Dog!
我在 Windows 上通过 Code::Blocks 使用 MingW。
最佳答案
它不是覆盖基类中的ToString
方法,因为基类方法不是虚拟的
。它只是用具有相同签名的函数隐藏该函数。
当您在 Dog
对象上调用 ToString()
时,将调用 Dog::ToString
方法。为什么它会调用任何其他 ToString()
方法; Dog::
声明是第一个找到的? virtual
分派(dispatch)只会在通过指针或对基类对象的引用被调用时发生(并且只需要)。
如果您需要在 Dog 对象上调用基类方法,则必须明确限定它。
d.Mammal::ToString()
关于c++ - 我如何在不使用 virtual 关键字的情况下覆盖这个 C++ 继承的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2993513/