2023/6/18
本篇章记录学习过程C++的基础概念和代码测试实现,还有很多需要补充。一是还不清楚,二是还没有学到。打算学习过程中后面再做补充。先看完《C++primer 》书之后再慢慢来添加补充
1.函数重载
- 一个函数名可以实现多个功能,这取决于函数参数不同来实现判断对应的功能,与返回值无关
- 函数可以重载,构造函数,成员函数都可以重载,但是,析构函数不能重载
#include <iostream>
using namespace std;
void print()
{
cout << "没有参数的print函数" << endl;
}
//int print() 错误
//{
// cout << "没有参数的print函数" << endl;
//}
void print(int a)
{
cout << "一个int参数的print函数"<< a << endl;
}
void print(string s)
{
cout << "一个string参数的print函数" << s << endl;
}
void print(int a,int b)
{
cout << "两个int参数的print函数" << a << b << endl;
}
int main()
{
// 通过传入参数的不同,可以调用不同的重载函数
print(1);
print(1,2);
print();
print("hjahhah");
return 0;
}
2.函数默认参数
函数可以设定默认值,当调用函数时,可以不传递参数,这样就会使用默认值。
注意点:
- 函数声明与定义分离,函数的参数默认值可以写在声明或定义处,但是只能出现一次
- 遵循向右原则,这个原则就是说某个参数设定了默认值,那么它的右边参数必须设定默认值
- 默认参数与函数重载一起使用时,需要注意不能发生二义性
void add(int a =1,int b=2,int c=3);
add(5);//这样是a为5,其余是默认b=2,c=3
add(7,8);//这样a=7,b=8,默认值c=3;
向右原则就是这样,a如果是默认值,那么b和c一定是默认值,不能b为默认值,c为传参。
#include <iostream>
using namespace std;
void show(int a = 1,int b = 2,int c = 3)
{
cout << a << " " << b << " " << c << endl;
}
void print(int a,int b);
void print(int a=1,int b =1)
{
cout << a << " " << b << endl;
}
void print2(int a = 1);
void print2(int a)
{
cout << a << endl;
}
int main()
{
show(); // 1 2 3
show(6); // 6 2 3
show(5,6); // 5 6 3
show(6,7,8); // 6 7 8
print(); // 1 1
print(2); // 2 1
print(2,3); // 2 3
print2(); // 1
print2(2); // 2
return 0;
}
#include <iostream>
using namespace std;
void show(int a = 1,int b = 2,int c = 3)
{
cout << a << " " << b << " " << c << endl;
}
void show()
{
cout << "哈哈哈哈哈" << endl;
}
int main()
{
// show(); 错误:二义性
return 0;
}
3.引用
&
可以改变引用的变量的值
注意点:
- 可以改变引用值,但是不能再次成为其他变量的引用
- 声明引用时,需要初始化
- 初始化的值不能为NULL
- 初始值是纯数字,需要加const关键字来修饰引用,表示引用的值不可变
- 可以将变量引用的地址赋值给一个指针,此处指针指向的还是原来的变量
- 可以对指针建立引用
- 使用const关键词修饰引用,此时不能通过引用修改数值,但是可以修改引用原变量的数值
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 2;
int& c = a; // c是a的引用
c = b; // 把b的值赋给c
cout << a << " " << &a << endl; // 2 0x61fe88
cout << b << " " << &b << endl; // 2 0x61fe84
cout << c << " " << &c << endl; // 2 0x61fe88
// int& c = b; 错误 变量c已经引用了a,现在再引用b
// &c = b; 错误
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a = 1;
// int& b; 错误
b = a;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
// int& a = NULL; 错误
return 0;
}
#include <iostream>
using namespace std;
int main()
{
// 常引用
const int &a = 123;
// a++; 错误
cout << a << endl; // 123
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int &b = a;
int* c = &b; // 指针c指向b
a++;
cout << *c << endl; // 2
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int* b = &a; // b是a的指针
int*& c = b; // c是b的引用
cout << &a