您好,我在继承和运算符重载方面遇到了一些麻烦,我希望你们能给我一些清晰的信息。
我有以下类(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();
在子类中,一切都会正常工作。
附带说明一下,我认为同时允许 const&
和 const*
是一种设计风格。你应该只允许 const&
版本并且让你的类的用户做 *ptr
如果他们有一个 ptr
指针。
关于c++ - 基类中运算符重载的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23569539/