c++ - 基类中运算符重载的问题

标签 c++ inheritance operator-overloading

您好,我在继承和运算符重载方面遇到了一些麻烦,我希望你们能给我一些清晰的信息。

我有以下类(class):

template<typename Type>
class Predicate{
public:
    Predicate() {};
    virtual ~Predicate(){};
    virtual bool operator()(const Type & value) = 0;
    virtual bool operator()(const Type * value){ //<-- this is the operator thats not working
        return (*this)(*value);
    };
};

template<typename Type>
class Always : public Predicate<Type>{
public:
    bool operator()(const Type & value){return true;}
    ~Always(){};
};

现在我希望我所有的谓词都接受引用和指针,但是当我测试类时:

int main(){
    Always<int> a;
    int i = 1000;
    a(&i);
    system("pause");
    return 1;
}

我收到以下错误:

test.cpp: In function 'int main()':
test.cpp:10:6: error: invalid conversion from 'int*' to 'int' [-fpermissive]
  a(&i);
      ^
In file included from test.cpp:2:0:
predicates.h:22:7: error:   initializing argument 1 of 'bool Always<Type>::operator()(const Type&) [with Type = int]' [-fpermissive]
  bool operator()(const Type & value){return true;}

最佳答案

这是因为当您声明时:

bool operator()(const Type & value){return true;}

在子类中,您隐藏/隐藏父类(super class)中运算符的任何其他重载。

如果你添加:

using Predicate<Type>::operator();

Live demo

在子类中,一切都会正常工作。


附带说明一下,我认为同时允许 const&const* 是一种设计风格。你应该只允许 const& 版本并且让你的类的用户做 *ptr 如果他们有一个 ptr 指针。

关于c++ - 基类中运算符重载的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23569539/

相关文章:

c++ - 使用运算符 == 的结构重载

c++ - 模数是否在幕后使用 float ?

c++ - 弱/强引用指针关系

inheritance - 创建一个继承自 "OpenLayers.Feature.Vector"的 JavaScript 类

c++ - Constexpr 类 : Inheritance?

c++ - 重载运算符试图将另一个重载运算符作为参数

c++ - 谁能详细告诉我 "*this pointer"?

c++ - Pythonic 方法来创建 vector vector 的空映射

python - 使用 __init__ 继承属性

C++ 运算符重载 Int 类型