1.基础语法
C++ 应用:操作系统、图形用户界面和嵌入式系统
C和C++区别:C++支持类和对象
C++语法
#include <iostream>
using namespace std;
int main(){
cout << "hello world!";
return 0;
}
int main () {
cout << "Hello World! "; return 0; }
Line1:#include <iostream>
是一个头文件库,可让我们使用输入和输出对象,例如 cout,头文件向 C++ 程序添加函数
Line2:using namespace std;
意味着可以使用标准库中的对象和变量的名称
Line3:空行,C++中空行不影响
Line4:int main()
总是会出现在C++程序中,称为function
,大括号 {} 内的任何代码都将被执行
Line5:cout
是与运算符 (<<
) 一起使用来输出文本的对象。注意:每个C++语句都以分号;
结束
Line6:return 0
结束主函数
#include <iostream>
int main(){
std::cout << "hello world!";
return 0;
}
using namespace std;
也可以用std::代替
C++输出
cout
对象,与运算符 (<<
) 一起使用来输出文本或值
可以一次性输出多行,但是C++不会自动分行
#include <iostream>
using namespace std;
int main(){
cout << "hello world!";
cout << "learning everyday";
return 0;
}
hello world!learning everyday
如果要分行,有两种方式:
- 插入转义序列
\n
:相当于回车 - 使用
endl
操纵器
cout << "hello world!\n";
cout << "hello world!" << endl;
hello world!
learning everyday
C++注释
单行注释://
多行注释:/*
和*/
#include <iostream>
using namespace std;
int main(){
// single line
cout << "hello world!" << endl;
/* multiple
line */
cout << "learning everyday";
return 0;
}
C++变量
int
:整型double
:浮点型char
:字符string
:字符串bool
:布尔
创建变量
type variableName = value;
int x = 5;
int y = 7;
int myAge = x + y;
string text = " years";
cout << "I am " << myAge << text << " old";
可以一行创建多个变量
int x = 5, y = 4, z = 6;
可以一行赋值多个变量相同的值
int x, y, z;
x = y = z = 5;
固定变量的值使用const
const int x = 5;
C++输入
cin
与运算符>>
一起用来读取输入
cin >> x;
C++数据类型
float
和double
的区别:float小数点后面最多6-7个数字,而double
可以有15个数字,使用double
计算更安全
浮点数可以用科学计数法,使用e
表示
float f1 = 35e3;
bool
类型只能赋值false
和true
bool learning = true;
单一字符可以用ASCII码表示
char a = 65;
cout << a;
A
创建string
时头文件要导入#include <string>
C++运算符
算术运算符
分配运算符
比较运算符
逻辑运算符
C++ 字符串
- 字符串连接:
+
或者append()
string firstName = "Zoey ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
string fullName = firstName + " " + lastName;
- 字符串长度:
length()
或者size()
string text = "learning everyday";
cout << text.length();
17
- 字符串读取:
[]
string text = "learning";
cout << text[2];
a
- 特殊字符串:字符串有双引号,因此文本中有一些特殊字符无法识别,需要专义字符
string text = "living like a \"tree\"";
cout << text;
living like a "tree"
- 输入字符串
cin输入字符串文本时默认以空格为结束符,因此只会读取第一个单词
string text;
cin >> text;
cout << text;
living like a tree
living
如果要读取一行,使用getline()
string text;
getline(cin, text);
cout << text;
living like a tree
living like a tree
C++数学
头文件#include "cmath"
,常见max
,min
,abs
C++条件语句
if else
语句
int main(){
int time = 22;
if (time < 10){
cout << "morning";
}else if (time < 20)