【发布时间】:2010-06-07 22:03:44
【问题描述】:
我有一个小程序来演示简单的继承。我正在定义一个派生自哺乳动物的 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!";
}
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。
【问题讨论】:
-
考虑屏蔽而不是覆盖。
-
天哪,我面前还有同样该死的任务。
标签: c++ inheritance