C++ 常用语法和语句详解及示例代码
#include
using namespace std;
// 主函数 int main() { // 输出文本 cout << 'Hello, World!' << endl;
// 变量声明和初始化
int num = 10;
double pi = 3.14159;
// 输入
cin >> num;
// 条件语句
if (num > 0) {
cout << 'Number is positive' << endl;
} else if (num < 0) {
cout << 'Number is negative' << endl;
} else {
cout << 'Number is zero' << endl;
}
// 循环语句
for (int i = 0; i < 5; i++) {
cout << i << ' ';
}
cout << endl;
// 数组
int arr[5] = {1, 2, 3, 4, 5};
// 循环遍历数组
for (int i = 0; i < 5; i++) {
cout << arr[i] << ' ';
}
cout << endl;
// 函数
int sum(int a, int b) {
return a + b;
}
// 函数调用
int result = sum(5, 10);
cout << 'Sum: ' << result << endl;
// 类的定义
class Rectangle {
int width, height;
public:
// 构造函数
Rectangle(int w, int h) {
width = w;
height = h;
}
// 成员函数
int area() {
return width * height;
}
};
// 创建对象
Rectangle rect(3, 4);
// 调用对象的成员函数
int area = rect.area();
cout << 'Area: ' << area << endl;
return 0;
}
这是一个简单的 C++ 程序,展示了一些常用的语法和语句,包括输出、变量、输入、条件语句、循环语句、数组、函数、类等。这些是 C++ 最基本的语法和语句,可以作为起点开始学习和掌握 C++ 编程。需要注意的是,C++ 语言更加丰富和复杂,还有更多高级特性和用法可以探索学习。
原文地址: https://www.cveoy.top/t/topic/dbbL 著作权归作者所有。请勿转载和采集!