要说的都在注释中 ↓
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
// C++中的引用
void quote()
{
// 在C++中如果要从键盘输入数据是用‘cin’函数
// 例:int a; cin >> a;
int a(100); // C++的另一种赋值方式
int &b(a); // 引用(b是a的引用或b引用a)符号'&';声明引用时必须进行赋值且不能为NULL
cout << b << endl; // 100
b++; // 可对引用的值进行修改但不能修改引用对象
cout << a << endl; // 101
int *p = &b; // 指针指向引用地址
(*p)++; //
cout << a << endl; // 102
int c = 10;
b = c; // 仅仅是赋值
cout << a << endl;
const int &d = 200; // 对数值建立引用时需要用const进行修饰表示常引用,常引用的值不可变
const int &e = a;
// e++ //错误 //使用常引用时,不能改变引用的值
a++; // 但可以改变原变量的值
// int &d = 200; //错误
cout << e << endl
<< d << endl; // 11 200
/*// 使用引用作为参数可以在参数传递的过程中减少副本的产生,相对指针而言其语法又更加简洁,因此可以使参数传递更加高效
// 需要注意的是,当引用作为函数参数时,如果能被const修饰,尽量使用const修饰,已达到引用安全性。*/
}
// double浮点型
void doublexing()
{
double decimals = 3.1415926;
cout << decimals << endl; // 3.14159
int narrow{decimals}; // C++11赋值方式(不稳定)//数据窄化
cout << narrow << endl; // 3
}
// string类的使用
void CharacterString()
{
string ch = "abcdefg";
cout << ch.size() << " " << ch.length() << endl; // 7 7
cout << "---------for循环---------" << endl;
for (int i = 0; i < ch.size(); i++)
{
cout << ch[i]; // abcdefg
}
cout << endl
<< "-----------for each循环------------" << endl;
for (char c : ch)
{
cout << c; // abcdefg
}
cout << endl;
cout << ch[1] << " "; // b //使用[N]取出数据
cout << ch.at(2) << endl; // c //还有at(N)取出数据
/*// 使用[]和at函数各有利弊,[]的优势是执行效率更高,at函数的优势是程序的安全性更高。综合而言在正规项目中推荐使用at函数,日常可以使用[]
// string是一个C++标准库中的字符串类,使用时要引入头文件#include <string>
// string可以在绝大多数情况下代替char*,不必担心内存是否足够、字符串长度等问题
// string类的遍历支持传统的循环(for、while),还支持C++特有的迭代器遍历,C++11又引入for-each循环。*/
}
/*内联函数在编译时会把函数体中的内容直接展开到主函数进行内容替换,牺牲编译的速度来换取执行的速度,因此内联函数的执行效率更高。
一般将代码长度较小(1-5行)且频繁使用的函数定义为内联函数。
成员函数默认都是内联函数。*/
inline void show1()
{
cout << "这样是内联函数,声明定义在一起" << endl; // 在函数前加inline即可将 函数定义为内联函数
}
void show2(); // 声明定义分离;一般定义的函数在主函数下面时使用
inline void show2()
{
cout << "这样是内联函数,声明和定义分离" << endl;
}
// C++中允许用同一个函数名定义多个函数,这就叫做函数重载,要求是函数名相同,但是参数不同(个数或类型
// 构造函数与成员函数也可以重载,但是析构函数不能重载
void overloaded(int a)
{
cout << "这个是函数重载" << endl;
}
void overloaded(int a, int b)
{
cout << "这个是函数重载2" << endl;
}
/*C++函数默认值,调用时如果传入参数,传入的参数会覆盖默认值;如果不传入参数,参数会使用默认值。
如果函数声明与定义分离,要求只能在声明处或定义处出现一次默认值的设定。
当一个参数设定了默认值之后,其右边(后边)所有的参数都必须设定默认值*/
void default1(int a, int b = 2, int c = 3)
{
cout << "--函数的缺省值(默认参数)--" << endl;
cout << a << " " << b << " " << c << endl;
}
// 声明定义分离(参数出现在一处即可)
void default2(int a = 1, int b = 2, int c = 3);
void default2(int a, int b, int c)
{
cout << "--声明定义分离的缺省函数参数--" << endl;
}
// 哑元函数
void DummyElement(int)
{
cout << "--哑元函数--" << endl
<< "哑元函数只有参数类型没有名称" << endl
<< "一般配合运算符重载使用" << endl
<< "保持函数的向前兼容性" << endl;
}
int main()
{
quote();
doublexing();
CharacterString();
show1();
show2();
overloaded(1);
overloaded(1, 2);
default1(0);
default2();
DummyElement(1);
return 0;
}
如果写的有不对的地方欢迎指出,感谢(*^__^*)