目录
C++基础介绍
C++特点
面向对象的三大特征
封装 继承 多态
面向对象与面向过程的区别
C++拓展的非面向对象的功能
引用
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int &b = a; // b是a的引用
cout << a << " " << &a << endl;
cout << b << " " << &b << endl;
return 0;
}
引用的性质
引用的参数
写一个函数,函数有两个参数a和b,函数的功能是交换两个传入的参数原来变量的值。
#include <iostream>
using namespace std;
void test2(int &a,int &b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
int main()
{
int a1 = 1;
int b1 = 2;
test2(a1,b1);
cout << "a1=" << a1 << endl;
cout << "b1=" << b1 << endl;
return 0;
}
指针和引用的区别
赋值
通常编程中使用=进行赋值操作,C++新增了以下赋值语法。(只能用于初始化)
#include <iostream>
using namespace std;
int main()
{
double b = 3.14;
int b1 = b;
int b2(b);
int b3{b}; // 升级:对数据窄化做出警告
cout << b << endl;
cout << b1 << endl;
cout << b2 << endl;
cout << b3 << endl;
return 0;
}
键盘输入
可以使用cin把用户在命令行中输入的内容赋值到变量中。cin与cout一样,都是属于头文件iostream中的标准输入输出流。
#include <iostream>
using namespace std;
int main()
{
int b;
cin>>b;
getchar();
string a;
cout << "请输入一个字符串" << endl;
getline(cin,a);
cout << "您输入的内容是:" << endl;
cout << a << endl;
return 0;
}
string字符串类
#include <iostream>
using namespace std;
int main()
{
string str = "helloworld";
cout << str.size() << endl;
cout << str.length() << endl;
cout << str[1] << endl;
cout << str.at(5) << endl;
return 0;
}
遍历方式
#include <iostream>
using namespace std;
int main()
{
string str = "helloworld";
for(int i = 0; i < str.size(); i++) //以for循环的方式进行输出字符串
{
cout << str.at(i);
}
cout << endl;
for(char i:str) //for each的方式进行循环遍历字符串
{
cout << i;
}
return 0;
}
字符串与数字转换
#include <iostream>
#include <sstream> // 字符串流
using namespace std;
int main()
{
string s = "123";
// int i = s; 错误
// string → int
istringstream iss(s);
int i;
iss >> i;
cout << i << endl;
// int → string
// string s2 = i; 错误
stringstream ss;
ss << i;
string s2 = ss.str();
cout << s2 << endl;
return 0;
}
函数
内联函数
函数重载overload
#include <iostream>
using namespace std;
void print_show(int i)
{
cout << "调用了int重载" << i << endl;
}
void print_show(string str)
{
cout << "调用了string重载" << str << endl;
}
void print_show(float f)
{
cout << "调用了float重载" << f << endl;
}
void print_show(double d)
{
cout << "调用了double重载" << d << endl;
}
int main()
{
print_show(11);
return 0;
}
哑元函数
#include <iostream>
using namespace std;
void print_show(int,int)
{
cout << "调用了int哑元函数1" << endl;
}
void print_show(int)
{
cout << "调用了int哑元函数2" << endl;
}
int main()
{
print_show(1,1);
return 0;
}
作用1:哑元函数用来区分函数重载
作用2:运算符重载中用到。