这不是家庭作业,只是我的 C++ 类(class)的一些训练练习,以便习惯继承和其他东西。所以练习的第一部分要求我们创建一个程序,它有一个类名 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;
}
程序打印出来
Width for a: 25 Perimeter for a: 10
Width for b: 120 Perimeter for b: 22
Area for c: 25 Perimeter for c: 10
出于某种原因,c 获取了 a 的值。有什么想法吗?
最佳答案
您忘记链接Square
的构造函数。您想将 Square
的构造函数更改为:
Square(int w) : Rectangle(w,w) {}
关于c++ - 继承和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6178771/