cap*_*ain 0 c++ inheritance constructor
这不是家庭作业,只是我的C++课程的一些训练练习,以便习惯于继承和东西.所以练习的第一部分要求我们创建一个程序,它有一个类名Rectangle,我们应该做构造函数getter和setter,找到区域和周长.这部分工作正常.练习的第二部分说要创建一个新的类名Square,它扩展Rectangle,它有一个构造函数,它将作为参数的正方形宽度.然后程序应该打印区域和周边.
#include <iostream>
using namespace std;
class Rectangular {
private:
int width;
int height;
public:
Rectangular () {
width = 5;
height = 5;
}
Rectangular (int w, int h) {
width = w;
height = h;
}
void setWidth (int w) {
width = w;
}
void setHeight (int h) {
height = h;
}
int getWidth () {
return width;
}
int getHeight () {
return height;
}
int getArea () {
return width*height;
}
int getPerimeter () {
return width+height;
}
};
class Square : public Rectangular{
public:
Square (int w) {
getWidth();
}
};
int main(int argc,char *argv[])
{
Rectangular a, b(10,12);
Square c(5);
cout << "Width for a: " << a.getArea() << " Perimeter for a: " << a.getPerimeter() << endl;
cout << "Width for b: " << b.getArea() << " Perimeter for b: " << b.getPerimeter() << endl;
cout << "Area for c: " << c.getArea() << " Perimeter for c: " << c.getPerimeter() << endl;
}
Run Code Online (Sandbox Code Playgroud)
该程序打印出来
Width for a: 25 Perimeter for a: 10
Width for b: 120 Perimeter for b: 22
Area for c: 25 Perimeter for c: 10
Run Code Online (Sandbox Code Playgroud)
由于某种原因,c得到a的值.有什么想法吗?
你忘了链接构造函数了Square.您想要更改Square要读取的构造函数:
Square(int w) : Rectangle(w,w) {}
Run Code Online (Sandbox Code Playgroud)