C++结构体内重载、this指针和友元函数(初步了解)

C++结构体内重载、this指针和友元函数(初步了解)

结构体内重载

  • 就笔者目前情况下看,当我需要对结构体进行排序时,需要另外创造一个函数来对结构体在某些值进行比较比较。而结构体内重载运算符能改变这样的编程路数,提高数据和数据之间的耦合程度。

this指针(暂时没用,类似python的self)

  • this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。

    所谓当前对象,是指正在使用的对象。例如对于stu.show();,stu 就是当前对象,this 就指向 stu。

友元函数

C++ 设计者认为, 如果有的程序员真的非常怕麻烦,就是想在类的成员函数外部直接访问对象的私有成员,那还是做一点妥协以满足他们的愿望为好,这也算是眼前利益和长远利益的折中。因此,C++ 就有了友元(friend)的概念。打个比方,这相当于是说:朋友是值得信任的,所以可以对他们公开一些自己的隐私。

格式

friend  返回值类型  函数名(参数表);

写法

一般写法

	bool operator >(const edge &a)const
	{
	return from > a.from;
    }

格式

返回类型 operator 运算符(const 结构体名称 &变量)const
{
    return 想要的比较方法;
}

友元写法

	friend bool operator > (edge a,edge b)
	{
		return a.from>b.from;
	}

测试代码

#include<iostream>
#include<stdio.h>
using namespace std;
struct edge{
	int from,to;
//	friend bool operator > (edge a,edge b)
//	{
//		return a.from>b.from;
//	}
	bool operator >(const edge &a)const
	{
	return from > a.from;
    }
};
int main()
{
    edge x,y;
	x.from=2;
	y.from=1;
	if(x>y)
	   cout<<"x";
	else 
	   cout<<"y";
	return 0;   	
}

输出

x

参考资料

原文地址:https://www.cnblogs.com/BeautifulWater/p/14489573.html