我有一个带有空虚函数 cmp 的父类 Obj
class Obj{
public:
virtual int cmp(const Obj& val) = 0;
...
};
我试图在子类 MyString 中定义该函数,而不是 const Obj&
作为参数,我使用 const MyString&
可能会出现错误“空虚函数 Obj::cmp
没有重新定义”class MyString : public Obj{
private:
...
public:
virtual int cmp(const MyString& val){
... using private values of MyString
}
};
那么我该如何解决这个问题,如果我有 3-4 个在该函数中使用自己变量的子类
最佳答案
我想到的一个例子是 curiously recurring template pattern.它是这样的:
#include <iostream>
#include <ostream>
template <typename T>
struct Base
{
virtual int cmp(T const &) = 0;
};
struct First : Base<First>
{
virtual int cmp(First const &);
};
int First::cmp(First const &)
{
std::cout << "First\n";
return 1;
}
struct Second : Base<Second>
{
virtual int cmp(Second const &);
};
int Second::cmp(Second const &)
{
std::cout << "Second\n";
return 2;
}
int main()
{
Base<First>* f1 = new First();
Base<First>* f2 = new First();
Base<Second>* s = new Second();
f1->cmp(*dynamic_cast<First*>(f2)); // if this will throw, use RAII instead of deletes below
// f1->cmp(*dynamic_cast<Second*>(f2)); error: cannot convert Second to First
delete f1;
delete f2;
}
关于c++ - 如何定义以派生类型作为参数的虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65212922/