c++ - 如何定义以派生类型作为参数的虚函数?

标签 c++ virtual-functions

我有一个带有空虚函数 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/

相关文章:

c++ - 协变返回类型和调度

c++ - C++ 对象引用的行为

c++ - 虚函数和普通函数有什么区别?

c++ - 数组中的元素无意中不断变化

c++ - 输入流在运算符中的目的 >> 重载

c++ - 为什么 const_cast<iterator>(const_iterator) 在 Visual C++ 6.0 中有效,但在 Visual Studio .NET 中无效?

c++ - 如果在 C++ 中的基类中添加虚函数或非虚函数,是否必须重新编译整个类层次结构?

c++ - 如何计算二维数组的结构张量?

c++ - gcc5.2 abi 更改 -> 兼容性有保证吗?

c++ - 抽象类引用