#include <iostream.h>class Building{private: int floor; int room; float area;public: Building(int f,int r,float a) { floor=f; room=r; area=a; } virtual void show() { cout<<"楼房的层数:"<<floor<<"房间数:"<<room<<"总平方数:"<<area<<endl; }};class House:public Building{private: int bedroom; int bathroom;public: House(int be,int ba) { bedroom=be; bathroom=ba; } void show() { cout<<"卧室的数量:"<<bedroom<<"浴室的数量:"<<bathroom<<endl; }};class Office:public Building{private: int fire; int telephone;public: Office(int fi,int te) { fire=fi; telephone=te; } void show() { cout<<"灭火器的数量:"<<fire<<"电话的数量:"<<telephone<<endl; }};void main(){ Building B(3,5,100),*p; House H(3,2); Office O(5,6); p=&B; p->show(); p=&H; p->show(); p=&O; p->show();}error C2512: 'Building' : no appropriate default constructor available为什么会出现这个
1 回答
MadMarical
TA贡献79条经验 获得超122个赞
你好。在c++中,继承不会继承父类的构造方法。但是在你调用子类方法时,会调用父类的构造函数。那么你这个问题就是因为继承之后没有显示的初始化你父类的构造方法导致了错误。比如你的house h(3,2)此时编译器先调用父类的构造方法,发现f,r,a 都不知道是什么,这样就产生了错误。正确的方法,请看例程1。
例程1
#include <iostream> using namespace std; class Building { private: int floor; int room; float area; public: Building(int f,int r,float a) : floor(f),room(r),area(a) { } virtual void show() { cout<<"楼房的层数:"<<floor<<"房间数:"<<room<<"总平方数:"<<area<<endl; } }; class House:public Building { private: int bedroom; int bathroom; public: House(int be,int ba) : Building(3,4,5) { bedroom=be; bathroom=ba; } void show() { cout<<"卧室的数量:"<<bedroom<<"浴室的数量:"<<bathroom<<endl; } }; class Office:public Building { private: int fire; int telephone; public: Office(int fi,int te) : Building(3,4,5) { fire=fi; telephone=te; } void show() { cout<<"灭火器的数量:"<<fire<<"电话的数量:"<<telephone<<endl; } }; int main() { Building B(3,5,100),*p; House H(3,2); Office O(5,6); p=&B; p->show(); p=&H; p->show(); p=&O; p->show(); return 0; }
- 1 回答
- 0 关注
- 1187 浏览
添加回答
举报
0/150
提交
取消