C++ 运算符重载 及 const 函数的应用

C++ 运算符重载

类头文件

#ifndef _FY_STUDENT_H_
#define _FY_STUDENT_H_

class Student
{
public:
	Student();
	Student(int grade);
	~Student();
	int GetGrade() const;
	void SetGrade(int grade);
private:
	int _grade;
};
#endif // _FY_STUDENT_H_

类 cpp 文件

#include "Student.h"
Student::Student()
{
}

Student::Student(int grade) : _grade(grade)
{
}

Student::~Student()
{
}

int Student::GetGrade() const
{
	return _grade;
}

void Student::SetGrade(int grade)
{
	_grade = grade;
}

成员函数实现重载

// 头文件添加
Student operator+(const Student & t1)
{
	Student tmp;
	tmp.SetGrade(this->_grade + t1.GetGrade());
	return tmp;
}

全局函数实现重载

// 头文件添加 友元类及函数声明
friend Student;
bool operator>(const Student &p2);
// cpp 文件添加函数实现
bool Student::operator>(const Student & p2)
{
	return this->GetGrade() > p2.GetGrade();
}

注意

函数参数使用 const + &

  1. const 是为了防止函数内部更改传入对象数据
  2. & 为了节省时间
  3. Typename func(T1, T2) cosnt;const 是为了防止func内部修改变量

使用此种方式时,函数内部若要调用传入对象的方法,应把方法声明为const类型。见注意(3)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值