我如何在不使用virtual关键字的情况下覆盖此C ++继承的成员函数? [英] How am i overriding this C++ inherited member function without the virtual keyword being used?
问题描述
我有一个小程序来演示简单的继承.我正在定义一个源自哺乳动物的Dog类.这两个类共享一个称为ToString()的简单成员函数.当我不使用virtual关键字时,Dog如何覆盖Mammal类中的实现? (我什至需要使用virtual关键字来覆盖成员函数吗?)
I have a small program to demonstrate simple inheritance. I am defining a Dog class which is derived from Mammal. Both classes share a simple member function called ToString(). How is Dog overriding the implementation in the Mammal class, when i'm not using the virtual keyword? (Do i even need to use the virtual keyword to override member functions?)
mammal.h
#ifndef MAMMAL_H_INCLUDED
#define MAMMAL_H_INCLUDED
#include <string>
class Mammal
{
public:
std::string ToString();
};
#endif // MAMMAL_H_INCLUDED
mammal.cpp
mammal.cpp
#include <string>
#include "mammal.h"
std::string Mammal::ToString()
{
return "I am a Mammal!";
}
dog.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
dog.cpp
#include <string>
#include "dog.h"
std::string Dog::ToString()
{
return "I am a Dog!";
}
main.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.
I'm using MingW on Windows via Code::Blocks.
推荐答案
它不是覆盖基类中的ToString
方法,因为基类方法不是virtual
.只是用具有相同签名的函数来隐藏该函数.
It's not overriding the ToString
method in the base class as the base class method is not virtual
. It is simply hiding that function with a function with an identical signature.
在Dog
对象上调用ToString()
时,将调用Dog::ToString
方法.为什么还要调用任何其他ToString()
方法? Dog::
声明是找到的第一个? virtual
仅在通过指针或对基类对象的引用进行调用时才会发生(并且仅在需要时)分派.
When you call ToString()
on a Dog
object the Dog::ToString
method is called. Why would it call any other ToString()
method; the Dog::
declaration is the first one found? virtual
dispatch would only happen (and only be needed) when being called through a pointer or reference to a base class object.
如果需要在Dog对象上调用基类方法,则必须明确地限定它.
If you needed to call the base class method on a Dog object you would have to qualify it explicitly.
d.Mammal::ToString()
这篇关于我如何在不使用virtual关键字的情况下覆盖此C ++继承的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!