这是您可以发布的一个较小的示例,它仍然可以证明您的问题:
#include <iostream>
using namespace std;
#include <cstring>
class scary {
char is[31];
char sez[31];
public:
scary() {
strcpy(is, "Creep");
strcpy(sez, "boooo");
}
scary(const char i[], const char s[])
{
strcpy(is, i); strcpy(sez, s);
}
virtual void sayis(ostream &os) const { os << is; }
void saysez(ostream &os) const // this is NOT virtual!!
{ os << sez; }
};
ostream &operator<<(ostream &os, const scary &x) {
x.saysez(os);
os << ", said the ";
x.sayis(os);
return os;
}
class ghost: public scary {
public:
ghost():scary("Ghost", "Boo!")
{
}
};
class witch: public scary {
char extra[31];
public:
witch(): scary("Witch", "Toil and Trouble") {
strcpy(extra, "Double, Double");
}
void saysez(ostream &os) const {
os << extra << " ";
scary::saysez(os);
}
};
int main() {
scary s;
ghost g;
witch w;
cout << s << '\n' << g << '\n' << w << '\n';
return 0;
}
输出:
boooo, said the Creep
Boo!, said the Ghost
Toil and Trouble, said the Witch
在witch
的构造函数中,您将sez
数组设置为"Toil and Trouble"
,然后在您打印出并调用打印出的函数中saysez
声明。发生这种情况是因为可以(但不鼓励)覆盖非虚拟成员函数。witch
extra
scary
saysez
sez