我有一个父类:
class Animal
{
public :
virtual void SetColor ( const string & col )
{
colour = col;
}
virtual void Greeting ( const string & name )
{
cout << "Hi I'm Animal" << endl;
}
protected:
string colour;
};
然后我有一个继承自Animal类的狗类。
例如:
class Dog : public Animal
{
};
如果我没弄错,Dog子类继承了父类Animal的所有内容,所以在这种情况下,Dog类继承了2个方法SetColor
和Greeting
以及string colour
。
是否有可能在父类Animal中禁止方法“问候”继承?
答案 0 :(得分:1)
您可以强制Dog
提供自己的Greeting
:
#include <iostream>
#include <string>
class Animal {
public:
virtual void SetColor(const std::string & col)
{
colour = col;
}
virtual void Greeting(const std::string & name) = 0;
protected:
std::string colour;
};
class Dog : public Animal {
virtual void Greeting(const std::string & name) override
{
std::cout << "Hi I'm a dog. My name is " << name << ". I was forced to provide this function.\n";
}
};
int main(void)
{
Animal *ptr = new Dog();
ptr->Greeting("Fluffy");
delete ptr;
return 0;
}