c++学习笔记-第二天

本文介绍了C++中的符号重载,通过一个person类展示了如何使用operator+进行自定义运算,并探讨了内置类型无法重载的问题。同时,通过示例解释了如何重载ostream的<<操作符实现自定义输出。此外,还讨论了智能指针SmartPoint的使用,展示了一个简单的showage方法调用。
摘要由CSDN通过智能技术生成

一、符号重载

形式如:

class person {
public:
	person() {};
	person(int h) { a = h; }
	person operator+(int num) {
		person tem;
		tem.a = a + num;
		return tem;
	};
	int a;
};
int main(void) {
	person p1(1);
	person p2 = p1+10;//相当于p2=p1.operator+(10);
	cout << p2.a << endl;
	return 0;
 
} 

由于其本质为函数调用,因此p1和整数位置无法调换,既图中所示p2 = p1+10不能写成p2 =10+p1;
函数可以重载,如

class person {
public:
	person() {};
	person(int h) { a = h; }
	person operator+(int num) {
		person tem;
		tem.a = a + num;
		return tem;
	};
	//函数重载
	person operator+(person p2) {
		person tem;
		tem.a = a + p2.a;
		return tem;
	}
	int a;
};

内置类型无法进行符号重载


案列:cout重载


class person{
public:
	person(){
	m_a=0;
	m_b=0;
	}
	person(int a,int b){
	m_a=a;
	m_b=b;
	}
	int m_a;
	int m_b;
}
ostream& operator(ostram& cout,person& p){
	cout<<"p.a为"p.a<<"p.b为"<<p.b;
	return cout;//实现链式输出
}
int main(void){
	person p;
	cout<<p<<endl;
	return 0;
}

对于全局函数的符号重载,比如上述重载,相当于将<<左边当作第一个参数,<<当作第二个参数传如重载函数;
对于重载函数,由于不需要改变传入参数的值,所以全部采用引用传递;

指针重载

class person{
public:
	person(){m_Age=0;}
	person(int age)
	{
		int m_Age=age;
	}
	boid showage(){
		cout<<"年龄为"<<this->age<<endl;
	}
	~person(){
		cout<<"函数的析构调用"<<endl;
	}
	int m_Age;
}
class SmartPonit{
public:
	person(){}
	person(person*p){
		m_Person=p;
	}
	person* operator->(){
		return this->m_Person
	}
private:
	person *m_Person;
}
int mian(void){
	SmartPoint sp=SmartPoint(new person(50));
	sp->showage();
return 0;}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值