跳转至

C++ 语法回顾

1.基础变化

#include <iostream> // 命名空间,std 标准库
using namespace std;// 命名空间,std 标准库
1
2
3
4
5
6
int main() {
    cout << "hello c++" << endl;// 输出,替代printf
    int x;
    cin >> x;// 输入,代替 scanf
    return 0;
}
bool类型,c 语言没有原生bool

2.引用 &

引用& 是变量别名,不是指针

1
2
3
int a = 10;
int &ref = a;
ref = 20;// a 变成 20

3.函数重载

1
2
3
4
5
6
void show(int a) {

}
void show(double a) {

}// 变量类型不一样也是重载

4.const 增强

1
2
3
4
const int a = 100;
const int &r = a;
const int *p;// 指向内容不可变,指针本身可变
int *const p;// 指针本身不可变,指向内容可变

5.类和对象

class Person {
private:
    int age;
public:
    // 构造函数
    Person() {
        age = 18;  
    }
    // 有参构造
    Person(int a){
        age = a;
    }
    // 成员函数
    void setAge(int a){
        age = a;
    }
    int getAge(){
        return age;
    }   
}

6.命名空间

1
2
3
4
5
namespace MySpace {
    int val = 10;
}
// 使用
MySpace::val

7.STL 标准容器

#include <vector>
#include <string>
#include <map>

std::vector<int> vec;// 动态数组,可自动扩容
vec.push_back(10);

std::string s = "hello";

std::map<int, std::string> map;