一.内联函数
inline
作用:编译时将函数体代码和实参代替函数调用语句
条件:一般用在代码比较简单的函数
语法:
- 关键字
inline
必须与函数实现/定义体放在一起才能使函数成为内联,将inline
放在函数声明前面不起任何作用 - 定义在类声明之中的成员函数将自动地成为内联函数
- 通常内联函数定义在头文件中。
#include<iostream> using namespace std; // #define MAX(a,b) ((a)>(b)?(a):(b)) 只负责替换 inline int MAX(int a,int b){//效果跟define一样,但当有A++时也可以编译 return a>b?a:b; } //或者用类:在类里写的函数都是内联 class Simple{ int n; public: Simple(int n):n(n){} void Print()const{ cout << n << endl; } }; int main(){ int n,m; cin >> n >> m; cout << MAX(n,m) << endl; }
二.运算符重载
语法:
返回值类型 operator 运算符(参数){
函数体
}
例:复数加法运算
Complex operator+(const Complex& c)const{
Complex res;
res.real = real + c.real;
res.iamg = imag + c.imag;
return res;
}
就可以实现:
Complex c1(1,2);
Complex c2(2,3);
Complex c = c1 + c2;
类的运算
流运算符
//全局函数(输出流运算符):
ostream& operator<<(ostream& os,const Complex& c){//都是引用,返回ostream
if(c.real != 0) os << c.real;
if(c.imag > 0) os << "+";
if(c.real != 0) os << c.imag << "i";
return os;//为链式
}
//可实现:
cout << c << endl; // cout.operator<<(c)
// operator<<(cout,c6)
说明:
- 不能重载的运算符:成员运算符
.
、作用域运算符::
、sizeof
、条件运算符?:
- 不允许用户自定义新的运算符,只能对已有的运算符进行重载
- 重载运算符不允许改变运算符原操作数的个数
- 重载运算符不能改变运算符的优先级
- 重载运算符函数不能有默认的参数,会导致参数个数不匹配