我创建了三个类:Shape
(基类),Rectangle
和Square
。我尝试从Shape
和Rectangle
的构造函数中调用Square
的构造函数,但编译器显示错误。
以下是代码:
class Shape{
public:
double x;
double y;
Shape(double xx, double yy) {x=xx; y=yy;}
virtual void disply_area(){
cout<<"The area of the shape is: "<<x*y<<endl;
}
};
class Square:public Shape{
public:
Square(double xx){ Shape(xx,xx);}
void disply_area(){
cout<<"The area of the square is: "<<x*x<<endl;
}
};
class Rectnagel:public Shape{
public:
Rectnagel(double xx, double yy){ Shape(xx,yy);}
void disply_area(){
cout<<"The area of the eectnagel is: "<<x*y<<endl;
}
};
int main() {
//create objects
Square sobj(3);
Rectnagel robj(3,4);
sobj.disply_area();
robj.disply_area();
system("pause");;//to pause console screen, remove it if u r in linux
return 0;
}
修改代码的任何想法或建议?
答案 0 :(得分:7)
要从孩子构建基础,请执行以下操作
//constructor
child() : base() //other data members here
{
//constructor body
}
在你的情况下
class Rectangle : public Shape{
public:
Rectangle(double xx, double yy) : Shape(xx,yy)
{}
void display_area(){
cout<<"The area of the eectnagel is: "<<x*y<<endl;
}
};
答案 1 :(得分:4)
这是正确的方法:
class Square:public Shape{
public:
Square(double xx) : Shape(xx,xx){}
void disply_area(){
cout<<"The area of the square is: "<<x*x<<endl;
}
};