Rectangle(int a, int b ) :Shape(a, b) {}的理解
时间: 2024-06-08 07:05:30 浏览: 11
这是一个 C++ 中的构造函数,用于初始化一个 Rectangle(矩形)对象。它的语法如下:
```c++
Rectangle(int a, int b) : Shape(a, b) {}
```
其中,`Rectangle` 是一个类名,`Shape` 是一个基类名。
该构造函数接受两个整数参数 `a` 和 `b`,然后使用冒号后面的语法 `: Shape(a, b)` 调用基类 `Shape` 的构造函数,并将参数 `a` 和 `b` 传递给基类构造函数进行初始化。
可以看到,在这个例子中,`Rectangle` 类继承自 `Shape` 类,并在其构造函数中调用了基类的构造函数,以便在创建 `Rectangle` 对象时对其进行初始化。
相关问题
Rectangle( int a=0, int b=0):Shape(a, b)
这是一个矩形类的构造函数,它有两个参数a和b,并且调用了基类Shape的构造函数,将a和b作为参数传递给它。
在这个构造函数中,默认为a和b赋值为0。如果在创建矩形对象时不传递任何参数,则a和b都将被设置为0。如果传递了参数,则a和b将被设置为相应的值。这种默认参数的使用可以方便地创建对象,同时也可以避免在某些情况下忘记传递参数而导致的错误。
#include <iostream> using namespace std; class Shape{ private: int x; int y; public: Shape(){} Shape(int a,int b):x(a),y(b) { } }; class Rectangle:public Shape{ private: int area,perimeter; public: Rectangle():Shape(x,y){ area=x*y; perimeter=(x+y)*2; } //Rectangle( int x,int y):Shape(x,y){ //area=x*y; // perimeter=(x+y)*2; //} void show(){ cout<<area<<" "<<perimeter<<endl; } }; int main(){ int x,y; cin>>x>>y; Shape x1(x,y); Rectangle x2(); x2.gets(); return 0: }
这段代码有一些问题,我先解释一下:
1. 在 Rectangle 类的构造函数中,需要先调用基类 Shape 的构造函数来初始化 x 和 y,但是在代码中没有传递 x 和 y 的值给 Shape。
2. 在 main 函数中,创建了一个 Shape 类型的对象 x1,但是没有使用。同时,创建了一个 Rectangle 类型的对象 x2,但是没有传递 x 和 y 的值给它。
3. 在 Rectangle 类中,定义了一个不带参数的构造函数,但是没有定义一个带参数的构造函数,所以如果要传递 x 和 y 的值,就需要再定义一个带参数的构造函数。
下面是修正后的代码:
```
#include <iostream>
using namespace std;
class Shape{
protected:
int x;
int y;
public:
Shape(int a=0, int b=0):x(a),y(b){}
};
class Rectangle:public Shape{
private:
int area, perimeter;
public:
Rectangle(int a=0, int b=0):Shape(a,b){
area = x * y;
perimeter = 2 * (x + y);
}
void show(){
cout << area << " " << perimeter << endl;
}
};
int main(){
int x, y;
cin >> x >> y;
Rectangle x2(x, y); // 创建 Rectangle 对象时传递 x 和 y 的值
x2.show(); // 输出结果
return 0;
}
```
现在这段代码就可以正确地创建 Rectangle 对象,并输出结果了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)