use*_*875 5 c++ operators overwrite pure-virtual
我正在尝试创建一个计数器接口,强制所有派生类实现此接口:
class CounterInterface
{
public:
virtual CounterInterface& operator ++ () = 0;
virtual CounterInterface operator ++ (int) = 0;
virtual CounterInterface& operator -- () = 0;
virtual CounterInterface operator -- (int) = 0;
virtual bool operator == ( const CounterInterface o ) const = 0;
virtual operator uint32_t () const = 0;
virtual void reset() = 0;
};
Run Code Online (Sandbox Code Playgroud)
但是,仅包含此类定义会导致下面的错误.
不幸的是,post inc无法定义为参考.
有任何想法如何解决这个鸡/蛋问题?
CounterInterface.h:25:29: error: invalid abstract return type for member function ‘virtual libceis::CounterInterface libceis::CounterInterface::operator++()’
CounterInterface.h:22:8: note: because the following virtual functions are pure within ‘libceis::CounterInterface’:
CounterInterface.h:25:29: note: virtual libceis::CounterInterface libceis::CounterInterface::operator++()
CounterInterface.h:26:29: note: virtual libceis::CounterInterface libceis::CounterInterface::operator++(int)
CounterInterface.h:27:29: note: virtual libceis::CounterInterface libceis::CounterInterface::operator--()
CounterInterface.h:28:29: note: virtual libceis::CounterInterface libceis::CounterInterface::operator--(int)
CounterInterface.h:29:17: note: virtual bool libceis::CounterInterface::operator==(libceis::CounterInterface) const
CounterInterface.h:30:12: note: virtual libceis::CounterInterface::operator uint32_t() const
CounterInterface.h:31:17: note: virtual void libceis::CounterInterface::reset()
CounterInterface.h:26:29: error: invalid abstract return type for member function ‘virtual libceis::CounterInterface libceis::CounterInterface::operator++(int)’
Run Code Online (Sandbox Code Playgroud)
你运气不好 您希望返回一个值,该值包含调用该函数的对象的动态类型.您不能:C++中的(非指针)值不能是协变返回类型,因为C++中的返回值不能与其静态类型具有不同的动态类型.
这与实现虚拟基本相同clone().它无法按价值返回.即使CounterInterface不是抽象类,你也会遇到麻烦,但是当代码无法编译时,你会注意到它,而是在返回的对象被切片时注意到它.
你可以做的是扩展设计.编写一个包含指向实例的(智能)指针的类CounterInterface.此类型可以按值返回,因此可以实现所需的接口.它可以通过调用纯虚函数CounterInterface *clone()(或unique_ptr<CounterInterface> clone())来实现,该函数分配并返回实现接口的具体类的新实例.对于作为虚函数运行的运算符,您可以将它们保持打开,CounterInterface并且您的包装类可以调用,或者您可以在虚拟接口中重命名它们:
class Counter {
unique_ptr<CounterInterface> ctr;
public:
Counter(unique_ptr<CounterInterface> c) : ctr(std::move(c)) {}
Counter(CounterInterface *c) : ctr(c) {}
Counter &operator++() {
ctr->increment(); // or ++(*ctr)
return *this;
}
Counter operator++(int) {
Counter ret(ctr->clone());
ctr->increment();
return ret;
}
operator uint32_t() const {
return *ctr;
}
void reset() {
return ctr->reset();
}
};
Run Code Online (Sandbox Code Playgroud)
虚拟operator==是一个完全独立的问题,我将留在网站上的其他问题.
顺便说一句,CounterInterface需要一个虚拟析构函数.
您不能使用纯虚拟成员函数实例化类。由于您无法创建它们,因此您也无法按值返回它们,就像在
virtual CounterInterface operator ++ (int) = 0;
virtual CounterInterface operator -- (int) = 0;
Run Code Online (Sandbox Code Playgroud)