gpt4 book ai didi

c++ - 禁止继承

转载 作者:行者123 更新时间:2023-11-28 05:41:40 26 4
gpt4 key购买 nike

我有一个父类:

 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 类的 Dog 类。

例如:

class Dog : public Animal
{

};

如果我没记错的话,Dog 子类继承了父类 Animal 的所有内容,所以在这种情况下,Dog 类继承了 2 个方法 SetColorGreeting 以及 字符串颜色

Is it possible to forbid method "Greeting" in parent class Animal to inherit?

最佳答案

你可以强制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;
}

关于c++ - 禁止继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36967347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com