c++类private例题
时间: 2023-10-29 07:04:45 浏览: 37
以下是一个使用C++类的私有变量和公共函数的例子:
```c++
#include <iostream>
using namespace std;
class Rectangle {
private:
int width, height;
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
int area() {
return width * height;
}
};
int main() {
Rectangle rect;
rect.setWidth(5);
rect.setHeight(7);
cout << "Area of the rectangle is : " << rect.area() << endl;
return 0;
}
```
在上面的示例中,Rectangle类有两个私有变量width和height,这意味着它们只能通过公共函数(即setWidth和setHeight)进行访问和修改。area函数是公共函数,它计算并返回矩形的面积。
在main函数中,我们创建一个名为rect的Rectangle对象,并通过setWidth和setHeight函数设置其宽度和高度。然后,我们调用area函数并打印结果。由于width和height是私有变量,我们不能在main函数中直接访问它们。