我有以下錯誤:
智能感知:返回類型與重寫虛擬函數的返回類型「計數器」不相同也不協變。「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