Dan*_*arb 1 c++ abstract-class
有没有办法强制在子类中实现方法,其中每个派生类的实现都有不同的签名?
我知道我可以使用纯虚拟来做到这一点:
class Base {
public:
virtual void getValue(string& s) = 0;
}
class Derived : public Base {
public:
void getValue(string& s);
}
Run Code Online (Sandbox Code Playgroud)
上面,基类中的纯虚拟 getValue 强制派生类实现 getValue。但我真正想做的是这样的:强制每个派生类实现 getValue() 但每个派生类都有不同的签名:
class Base {
public:
void getValue() = 0;
}
class Derived_A : public Base {
public:
void getValue(string& s);
}
class Derived_B : public Base {
public:
void getValue(int *j);
}
Run Code Online (Sandbox Code Playgroud)
上述问题在于,由于名称修改,每个签名实际上都是不同的函数,因此 Derived_A 和 Derived_B 继承 getValue() = 0 并且编译器认为它们也是抽象的。
我一直在尝试一些不同的方法来做到这一点,但在我看来没有办法做到这一点。我想我不应该在基类中声明 getValue ,然后确保每个派生类都实现其版本。
如果使用CRTP对您有用,您可以使用:
#include <string>
template <typename TypeSelector>
class Base {
public:
using type = typename TypeSelector::type;
virtual void getValue(type t) = 0;
};
struct TypeSelector_A {
using type = std::string&;
};
class Derived_A : public Base<TypeSelector_A> {
public:
void getValue(std::string& s) { /* Add real implementation */ }
};
struct TypeSelector_B {
using type = int*;
};
class Derived_B : public Base<TypeSelector_B> {
public:
void getValue(int* j) { /* Add real implementation */ }
};
int main()
{
Derived_A a;
Derived_B b;
}
Run Code Online (Sandbox Code Playgroud)