其它的和C相差无几,参照b站cpp课程-哔哩编程学院,菜鸟cpp教程,
【Visual Studio 2022】常用快捷键和一些小技巧。
1. cpp 基本输入输出
#include <iostream>
using namespace std;
class A {
public:
};
class A1 :public A {
};
int main()
{
return 0;
}
1.1 cout详解
cout ;
cout << "Hello World" ;//直接字符串
cout << name ; //字符串地址
<< endl ://换行
1.2 不一样的数据类型
cpp中 int x{ }
和 int x = 0
是一回事么?。
int a{
10}; //int a=10; 效果一样
int b{
};// int b{0}; int b=0;
1.3 见多识广
return; return 0; return -1; return 1之间的区别。
void test01()
{
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return; //void函数返回,退出整个程序。
}
}
2. 接轨C语言
1. bool类型
相比 int 的0,1更节约内存。非0即1,方便判断
#include <iostream>
using namespace std;
int main()
{
bool a = true; //ture就是1
a = false; //false就是0
a = 123; //非0即1
a = 3.14;
cout << a << endl << sizeof(bool); //长度都是1个字节。
return 0;
}
2. 内联函数
一般用于简单函数,占用内存不大的。
就函数声明、函数定义前加上关键字:inline
#include <iostream>
using namespace std;
inline void func(int num); //声明
int main()
{
func(4);
return 0;
}
inline inline void func(int num) {
//定义
cout << num ;
}
3. 函数重载
同一项目,函数名字可以重复。
但函数的参数列表必须不同:不同个数,同个数对应位置类型不同。
只有返回值不同不行!
4. 函数参数缺省
声明函数某个参数时,指定一个默认值,调用时缺省则默认。
从右到左排!
#include <iostream>
using namespace std;
void func(int num, float val = 2, double db = 3);//声明处默认
int main()
{
func(4); //调用时 参数缺省
return 0;
}
void func(int num, float val, double db) {
cout << num <<endl << val <<endl << db;
}
5. 引用
5.1 变量、对象取别名
指向同一地址,心连心,1变则2变,定义引用的时候必须初始化。
#include <iostream>
using namespace std;
class Person {
public:
int age;
string name;
};
int main()
{
int a1 = 0;
int a2 = 3;
int& b1 = a1; //int* const b1 = &a1; 使用时直接用b1,用*b1会报错!
int& b2 = a2; //引用变量,必须同时初始化
cout << b1 << endl; //0
cout << b2 << endl; //3
b1++; //心连心
cout << a1 << endl; //1
b1 = a2; //赋值!不能更改引用。
cout << a1 << endl; //3
b1 = b2; //同 b1 = a2,赋值,不能更改引用
b1++;
cout << a1 << endl; //4
cout << a2 << endl; //3
Person Tom;
Person& Tomc = Tom;
Tomc.age = 2;
cout << Tom.age; //2
return 0;
}
5.2 引用函数传参
#include<iostream>
using namespace std;
//1. 值传递
void mySwap01(int a, int b) {
int temp = a;
a = b;
b = temp;
}
//2. 地址传递
void mySwap02(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
//3. 加个引用,让形参能够改变实参!
void mySwap03(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int a = 10;
int b = 20;
mySwap01(a, b); //10,20 不能交换
cout << "a:" << a << " b:" << b << endl;
mySwap02(&a, &b);//20,10 指针肯定可以交换
cout << "a:" << a << " b:" << b << endl;
mySwap03(a, b); //10,20 引用也能交换!比指针简洁。
cout << "a:" << a << " b:" << b << endl;
return 0;
}
5.3 引用作函数返回值
#include<iostream>
using namespace std;
//返回局部变量引用
int& test01() {
int a = 10; //局部变量
return a;
}
//返回静态变量引用
int& test02() {
static int a = 20; //静态变量,相当于全局变量!
return a;
}
int main() {
//不能返回局部变量的引用
int& ref = test01(); //局部变量,函数执行完就释放内存了!
cout << "ref = " << ref << endl;
cout << "ref = " << ref << endl;
//如果函数做左值,那么必须返回引用
int& ref2 = test02(); //别名,左右一样
cout << "ref2 = " << ref2 << endl;
cout << "ref2 = " << ref2 << endl;
test02() = 1000; //左值
cout << "ref2 = " << ref2