C++是一种高效、通用的编程语言,广泛应用于操作系统、驱动、游戏、GUI、嵌入式系统等领域。学习好C++语法,可以帮助我们更好地理解和实现算法,更快速、高效地完成工程。
int a = 10;
double b = 3.14;
char c = 'A';
// 算术运算符
int sum = a + b;
int diff = a - b;
double mul = a * b;
double div = a / b;
// 逻辑运算符
bool b1 = true;
bool b2 = false;
bool b3 = b1 && b2;
bool b4 = b1 || b2;
bool b5 = !b1;
int a = 10, b = 20;
if (a > b) {
cout << "a > b" << endl;
} else {
cout << "a <= b" << endl;
}
- for循环:执行指定次数的循环。
for (int i = 0; i < 10; i++) {
cout << i << endl;
}
- while循环:在满足条件的情况下反复执行代码块。
int i = 0;
while (i < 10) {
cout << i << endl;
i++;
}
- switch语句:根据不同的条件执行相应的代码块。
int a = 3;
switch (a) {
case 1:
cout << "a = 1" << endl;
break;
case 2:
cout << "a = 2" << endl;
break;
default:
cout << "a is not 1 or 2" << endl;
break;
}
class Student {
public:
string name;
int age;
void study() {
cout << name << " is studying" << endl;
}
void showInfo() {
cout << "name: " << name << ", age: " << age << endl;
}
};
我们可以创建一个Student对象,通过对象来调用其属性和方法:
Student stu;
stu.name = "Tom";
stu.age = 18;
stu.study();
stu.showInfo();
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for (int i = 0; i < v.size(); i++) {
cout << v[i] << endl;
}
STL库中还有很多有用的函数和算法,比如sort、find、accumulate等,可以大大提高编程效率和代码的可读性。
本文链接:http://task.lmcjl.com/news/36.html