我有以下错误:
智能感知:返回类型与重写虚拟函数的返回类型“计数器”不相同也不协变。“Counter :: operator ++”返回类型与返回类型(运算符++)不一致或不一致
这里是我的项目的头。
counter.h
/* Header file of Counter Class*/
#pragma once
#include <iostream>
using namespace std;
//Class definition
class Counter {
friend ostream &operator<<(ostream &out, const Counter &c);
public:
Counter(int n0 = 0);
virtual Counter &operator++();
virtual Counter operator++(int);
void reset();
int getCount() const;
private:
int count;
};
LimitedCounter.h
#pragma once
#include "counter.h"
class LimitedCounter : public Counter{
friend ostream &operator<<(ostream &out, const LimitedCounter &c);
public:
LimitedCounter(int low, int up);
void reset();
LimitedCounter& operator++();
LimitedCounter operator++(int); // error here
operator int() { return getCount(); };
int getCount() const { return Counter::getCount(); };
private:
int upper;
};
和实现
counter.cpp
/* Implementation of Counter Class*/
#include "counter.h"
#include <iostream>
Counter:: Counter(int n0) {
count = n0;
}
Counter& Counter::operator++() {
count++;
return *this;
}
Counter Counter::operator++(int) {
Counter old = *this;;
count++;
return old;
}
void Counter::reset(){
count = 0;
}
int Counter::getCount() const{
return count;
}
ostream &operator<<(ostream & out, const Counter &c) {
out << "\nCounter value is now " << c.count ;
return out;
}
LimitedCounter.cpp
#include "LimitedCounter.h"
LimitedCounter::LimitedCounter(int low, int up) : Counter(low), upper(up) {}
LimitedCounter& LimitedCounter::operator++() {
if (getCount() < upper) {
Counter::operator++();
}
return *this;
}
LimitedCounter LimitedCounter::operator++(int) {
if (getCount() < upper) {
LimitedCounter old = *this;
Counter::operator++(0); // question?
return old;
}
else {
return *this;
}
}
void LimitedCounter::reset() {
Counter::reset();
}
//friend function
ostream &operator<<(ostream &out, const LimitedCounter &c) {
out << c.getCount() << endl;
return out;
}
我得到的错误:
错误C2555: 'LimitedCounter ::运算++':重写虚函数返回类型不同,不从协变 '反::运算++'
当我在counter.h的后递增删除虚拟那么有没有错误可言。所以一切工作正常预增量。所以我不知道是不是因为我如何实现后递增?而且,当我重写后递增(操作++(INT)),是不是我写的是这样的:
Counter::operator++(0);
谢谢你帮助我。
多态性不与某些事情拌匀。如果您在指向“LimitedCounter”对象的“Counter”引用上调用“op ++”,那么调用者代码如何知道需要预留多少空间?有足够的'Counter'对象,还是什么? –
这是一个并不真实的实现细节 - 如果编译器真的想要,它可以很容易地透明间接。真正的问题是它是一个计数器值,因此不能是有限计数器或任何其他东西,除了计数器。 – Puppy