调用TestComp的构造函数时出现编译错误,设计如下:
template <typename R>
class IComparable
{
public:
virtual bool Equals(const R & rhs) const = 0;
};
class TestComp : IComparable<char*>
{
public:
std::string x;
TestComp(std::string & a)
{
x = a;
}
virtual bool Equals(const char* & a) const
{
return x == std::string(a);
}
};
错误:
error C2259: 'TestComp2' : cannot instantiate abstract class due to following members:'bool IComparable<R>::Equals(const R &) const' : is abstract with [ R=char * ]
我无法理解,因为我在定义 TestComp::Equals 时使用的签名似乎与 IComparable::Equals 相同。
我在尝试各种变通方法时注意到的一件事是,如果我使两个函数“Equals(R & rhs) const”从参数中删除 const,那么我就不会再收到此错误。
谁能帮我理解这种行为?
最佳答案
派生方法的签名不正确。应该是
virtual bool Equals(char* const& a) const
请注意,const
被“应用”到下一个最接近的 *
和 &
和 &&
之前的类型>,即,
const char* &
,等同于char const* &
,表示对char
的常量指针的引用>.char* const&
表示对指向char
的指针的常量引用。const R&
,相当于R const&
,表示对R
的常量引用。
关于c++ - 从纯虚拟模板类派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19110681/