以下代码会报错
#include <iostream> using namespace std; class Sofa { public: Sofa(); ~Sofa(); void sit() { cout<<"sit!"<<endl; } void setWeight(int w) { this->weight = w; } int getWeight() { return this->weight; } void showWeight() { cout<<this->weight<<endl; } private: int weight; }; Sofa::Sofa() { } Sofa::~Sofa() { } class Bed { public: Bed(); ~Bed(); void lie() { cout<<"lie!"<<endl; } void setWeight(int w) { this->weight = w; } int getWeight() { return this->weight; } void showWeight() { cout<<this->weight<<endl; } private: int weight; }; Bed::Bed() { } Bed::~Bed() { } class Sofabed : public Bed, public Sofa { public: Sofabed(); ~Sofabed(); void showWeight() { Sofa::showWeight(); cout<<"&&"<<endl; Bed::showWeight(); } private: }; Sofabed::Sofabed() { } Sofabed::~Sofabed() { } int main () { Sofabed myfur; myfur.sit(); myfur.lie(); myfur.setWeight(12); // 不清楚是哪个函数,会报错 myfur.Sofa::setWeight(12); // 要写 [obj.classname::function(12)] ; myfur.Sofa::showWeight(); myfur.Bed::setWeight(99); myfur.Bed::showWeight(); // sofa & bed 的 member 是两个不一样的。 // 也可以在 derived class 里,overload 名字冲突的函数 myfur.showWeight(); system("pause"); return 0; }
修改的代码
#include <iostream> using namespace std; class Sofa { public: Sofa(){ cout<<"Sofa()"<<endl; } ~Sofa(){ cout<<"~Sofa()"<<endl; } void sit() { cout<<"sit!"<<endl; } void setWeight(int w) { this->weight = w; } int getWeight() { return this->weight; } void showWeight() { cout<<this->weight<<endl; } private: int weight; }; class Bed { public: Bed(){ cout<<"Bed()"<<endl; } ~Bed(){ cout<<"~Bed()"<<endl; } void lie() { cout<<"lie!"<<endl; } void setWeight(int w) { this->weight = w; } int getWeight() { return this->weight; } void showWeight() { cout<<this->weight<<"\n\n"<<endl; } private: int weight; }; class Sofabed : public Bed, public Sofa { public: Sofabed(){ cout<<"Sofabed()\n\n"<<endl; } ~Sofabed(){ cout<<"~Sofabed()"<<endl; } void showWeight() { cout<<"Sofa::showWeight()"; Sofa::showWeight(); cout<<"&"; cout<<this->weight; cout<<"&"<<endl; cout<<"Bed::showWeight()"; Bed::showWeight(); } void setWeight(int w) { this->weight = w; } private: int weight; }; int main () { Sofabed myfur; myfur.sit(); myfur.lie(); myfur.Sofa::setWeight(12); // 要写 [obj.classname::function(12)] ; myfur.Sofa::showWeight(); myfur.Bed::setWeight(99); myfur.Bed::showWeight(); // sofa & bed 的 member 是两个不一样的。 myfur.setWeight(199); // 修改后 myfur.showWeight(); return 0; }
由于,继承后,编译器不清楚setWeight函数是哪个类的,所以报错了,修改后,我们调用的就是实例化的那个类的函数,所以不会报错