gpt4 book ai didi

c++ - 要求基类中的方法被其所有子类覆盖

转载 作者:行者123 更新时间:2023-11-27 23:23:36 24 4
gpt4 key购买 nike

在 C++ 中,是否可以要求基类中的方法被其所有派生类覆盖而不使其成为纯虚方法?

#include <iostream>
using namespace std;

class BaseClass{
public:
int printStuff(){ //find some way to require all derived classes to override this method
cout << "Printing some stuff";
}
};

class DerivedClass: public BaseClass{

};

int main(){
cout << "Hello World!";
return 0;
}

最佳答案

我知道你说过你不想使用纯虚函数,但你可以使用纯虚函数并且仍然给方法一个定义,如果那是你想要做的(不确定你是否已经知道):

class BaseClass{
public:
virtual int printStuff() = 0;
};

// give the pure virtual function an implementation
int BaseClass::printStuff() {
cout << "Printing some stuff";
}

class DerivedClass: public BaseClass{
// compiler error; DerivedClass must override printStuff
};

class DerivedClass2: public BaseClass{
public:
int printStuff() {
return BaseClass::printStuff(); // use the base class's implementation
}
};

关于c++ - 要求基类中的方法被其所有子类覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066457/

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