子类作为超类成员函数中的参数,C++

Subclass as argument in superclass's member function, C++

我是 OOP 的新手,正在从事 C++ 项目。我将我的问题分离出来以便于回答,但这是真实情况:

我有一个 superclass 成员函数,它修改调用它的对象内部的值。修改基于来自同一 class 的另一个对象的值。该对象作为唯一参数提供给函数。如:
void BaseClass::function(BaseClass x) {}

不过,我创建了一个子class。而如果参数是subclass类型,我也想修改它的unique属性
void BaseClass::function(DerivedClass x) {}

问题是subclass显然是在代码后面定义的

我不想把它作为两个单独的方法,因为计算算法已经写在里面了,而且我搜索的解决方案不需要在已经使用函数的地方更改代码.此外,想到的所有其他可能性(例如使用 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;    
}    

标准的做法是什么?

您可以将 test2 设为模板,并确保它仅用于从 Base:

派生的类型
template<typename Derived>
void test2(Derived &example) 
{ 
  static_assert(std::is_base_of_v<Base, Derived>);
  std::cout << example.getNumber(); 
}

这是一个demo