我在.HPP文件中創建了一個具有虛函數的派生類,然後在類的.CPP文件中給它一個默認返回值。接下來,我創建了一個繼承後一個派生類的類,並重載了它的虛函數,給它一個新的返回值。但是,返回值並不總是相同的(默認返回值或重載返回值)。有人可以幫我修復我的代碼或找到問題。謝謝。C++:派生的虛函數返回奇怪的結果
注意:我提供了示例代碼,我相信這將足以顯示問題。
#include <iostream>
#include <sstream>
using std::cout;
using std::ostream;
class Fruit;
class Apple;
class Fruit
{
public:
int Type;
Fruit();
~Fruit();
Fruit(int = 0);
virtual const int getVal() const;
};
class Apple : public Fruit
{
public:
Apple();
~Apple();
const int getVal() const;
};
Fruit::Fruit() : Type(0) {}
Fruit::~Fruit() {}
Fruit::Fruit(int type) : Type(type) {}
//const int Fruit::getVal() const { return 0; } //Uncommenting this results in function //always returning ZERO; even in Apple::getVal().
const int Fruit::getVal() const { return Type; }
Apple::Apple() : Fruit(1) {}
Apple::~Apple() {}
const int Apple::getVal() const { return Type; }
ostream& operator<<(ostream& a, Fruit b)
{
return a << b.getVal();
}
int main(int *argc, char **argv)
{
cout << Apple() << "\n\n";
#ifdef _WIN32
system("pause");
#endif
return 0;
}
您不能重載或覆蓋返回類型。 (但是在你提供的代碼中,你似乎試圖做到這一點,你的代碼與解釋不符。幸運的是,你的理論不在基地,正如答案所解釋的那樣:D) – 2011-04-22 03:33:38