[英]trouble with operator overloading in baseclass
嗨,我在继承和运算符重载方面遇到了麻烦,希望你们能给我一些清晰度。
我有以下课程:
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;}
在子类中,您要隐藏 / 隐藏超类中运算符的任何其他重载。
如果添加:
using Predicate<Type>::operator();
在子类中,一切正常。
从侧面讲,我认为同时允许const&
和const*
是一种设计味道。 您应该只允许const&
版本,并允许类的用户执行*ptr
如果他们具有ptr
指针)。
模板和运算符重载掩盖了这里的实际问题。 看一下产生相同错误的这段小代码:
void f(int &);
int main()
{
int *ptr;
f(ptr);
}
编译器不会让你通过凡在预期的指针。 这就是您尝试对派生类进行的操作。 当你对一个具体的操作Always
,的基本版本operator()
不考虑。
查看当您对基类的指针(或引用)进行操作时,情况如何变化:
int main(){
Predicate<int> *ptr = new Always<int>;
int i = 1000;
(*ptr)(&i);
delete ptr;
}
编译良好,因为现在考虑将基类运算符用于重载解析。 但这只是为了使您更好地理解问题。 该解决方案是应用的非虚拟接口成语 。 使您的操作员不是虚拟的,并根据私有虚拟功能实施它们:
template<typename Type>
class Predicate{
public:
Predicate() {};
virtual ~Predicate(){};
bool operator()(const Type & value) { return operatorImpl(value); }
bool operator()(const Type * value) { return operatorImpl(value); }
private:
virtual bool operatorImpl(const Type & value) = 0;
virtual bool operatorImpl(const Type * value) {
return (*this)(*value);
}
};
template<typename Type>
class Always : public Predicate<Type>{
public:
~Always(){};
private:
bool operatorImpl(const Type & value){return true;}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.