C++语言入门(六)内联函数和运算符重载

一.内联函数

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、条件运算符?:
  • 不允许用户自定义新的运算符,只能对已有的运算符进行重载
  • 重载运算符不允许改变运算符原操作数的个数
  • 重载运算符不能改变运算符的优先级
  • 重载运算符函数不能有默认的参数,会导致参数个数不匹配
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值