我在.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