#include <iostream>
using namespace std;
// 定义一个简单的类来演示C++的基本语法
class HelloWorld {
public:
// 构造函数
HelloWorld() {
message = "Hello, World!";
}
// 成员函数,用于输出消息
void printMessage() {
cout << message << endl;
}
private:
string message; // 成员变量
};
int main() {
// 创建HelloWorld类的对象
HelloWorld hello;
// 调用成员函数打印消息
hello.printMessage();
return 0;
}
#include <iostream>
:引入标准输入输出流库,以便使用 cout
和 cin
。using namespace std;
:使用标准命名空间,避免每次调用标准库中的对象或函数时都要加前缀 std::
。class HelloWorld
:定义一个名为 HelloWorld
的类,包含一个构造函数、一个成员函数和一个私有成员变量。HelloWorld()
:构造函数,用于初始化类的成员变量 message
。void printMessage()
:成员函数,用于输出保存在 message
中的消息。main()
函数:程序的入口点,创建 HelloWorld
类的对象并调用其成员函数 printMessage
来输出消息。这个示例展示了 C++ 中类和对象的基本用法。
上一篇:c++ cin
下一篇:c++ 11
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站