【发布时间】:2021-01-22 18:16:58
【问题描述】:
我是 OOP 的新手,我正在开发一个 C++ 项目。我隔离了我的问题以便于回答,但这是真实情况:
我有一个超类成员函数,它修改调用它的对象内的值。修改基于来自同一类的另一个对象的值。该对象作为唯一参数提供给函数。如: void BaseClass::function(BaseClass x) {}
但是,我创建了一个子类。而如果参数是子类类型,我也想修改它的唯一属性。 void BaseClass::function(DerivedClass x) {}
问题是子类显然是在代码后面定义的。
我不希望它作为两个单独的方法,因为计算算法已经写在里面,而且我搜索的解决方案不需要在函数已经使用的地方更改代码。此外,想到的所有其他可能性(例如使用typeid())看起来都很愚蠢。
#include <iostream>
#include <string>
class Base
{
protected:
//common attribute
const std::string name;
public:
//constructor for common attribute
Base(const std::string nameString) : name(nameString) {}
//getter
std::string getName() { return name; }
//superclass as parameter
void test1(Base &example) { std::cout << example.getName(); }
//subclass as parameter (I'd want the line below to work)
//void test2(Derived &example) { std::cout << example.getNumber(); }
};
class Derived : private Base
{
protected:
//unique attribute
const std::string number;
public:
//constructor
Derived(const std::string nameString, const std::string numberString) : Base(nameString),
number(numberString) {}
//getter for unique attribute
std::string getNumber() { return number; }
};
int main ()
{
Base object = Base("whatever");
Base baseParameter = Base("base");
Derived derivedParameter = Derived("derived", "12");
object.test1(baseParameter);
//object.test2(derivedParameter);
return 0;
}
标准的做法是什么?
【问题讨论】: