// 示例代码:C++ 中的简单类定义和使用
#include <iostream>
using namespace std;
// 定义一个简单的类
class Rectangle {
// 私有成员变量
int width, height;
public:
// 构造函数
Rectangle(int x, int y) : width(x), height(y) {}
// 成员函数,计算面积
int area() {
return width * height;
}
// 成员函数,打印矩形信息
void display() {
cout << "Rectangle Width: " << width << endl;
cout << "Rectangle Height: " << height << endl;
cout << "Rectangle Area: " << area() << endl;
}
};
int main() {
// 创建 Rectangle 对象
Rectangle rect(10, 5);
// 调用成员函数
rect.display();
return 0;
}
Rectangle 类包含两个私有成员变量 width 和 height,用于存储矩形的宽度和高度。Rectangle(int x, int y) 是类的构造函数,用于初始化对象时设置宽度和高度。area() 计算矩形的面积,display() 打印矩形的信息(宽度、高度和面积)。main() 函数中,创建了一个 Rectangle 对象,并调用了 display() 函数来输出矩形的相关信息。这段代码展示了如何在 C++ 中定义类、构造函数以及成员函数的基本用法。
上一篇:c++ map insert
下一篇:智能指针c++11
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站