#include<iostream> using namespace std; class R{ int len,w; public: R(int len,int w); int getArea(); }; R::R(int len,int w){ } int R::getArea(){ return (this->len)*(this->w); } int main(){ R r1(2,5),r2(3,6); cout<<"First Area is "<< <<endl; cout<<"Second Area is "<< <<endl; return 0; }
时间: 2024-01-23 15:01:35 浏览: 93
这段代码定义了一个名为 R 的类,该类具有两个私有数据成员 len 和 w,分别表示矩形的长度和宽度。该类还有一个公有成员函数 getArea(),用于计算并返回矩形的面积。其中,类的构造函数 R(int len, int w) 用于初始化矩形的长度和宽度。
在 main 函数中,创建了两个 R 类的实例 r1 和 r2,并分别传入了不同的长度和宽度,以初始化这两个矩形对象。接着,使用 cout 输出了这两个矩形对象的面积,即调用了矩形对象的 getArea() 函数。
不过需要注意的是,R 类中的构造函数 R(int len, int w) 并没有将 len 和 w 两个私有数据成员初始化为传入的值,因此在调用 getArea() 函数时,会出现未定义的行为。
正确的 R 类构造函数和 getArea() 函数的实现应该如下所示:
```
class R {
int len, w;
public:
R(int len, int w) {
this->len = len;
this->w = w;
}
int getArea() {
return this->len * this->w;
}
};
int main() {
R r1(2, 5), r2(3, 6);
cout << "First Area is " << r1.getArea() << endl;
cout << "Second Area is " << r2.getArea() << endl;
return 0;
}
```
在这个例子中,创建了两个 R 类的实例 r1 和 r2,并分别传入了不同的长度和宽度,以初始化这两个矩形对象。接着,使用 cout 输出了这两个矩形对象的面积,即调用了矩形对象的 getArea() 函数,输出结果为:
```
First Area is 10
Second Area is 18
```
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)