struct部分用法

一.初始化
1.创建struct时自动初始化。
2.构造函数初始化:

struct node{
	int a,b;
	node(){
		a=0;b=1;
	}
}s;

构造函数特点:

  • 与struct同名
  • 无返回值

3.默认构造函数:

struct node{
	int a,b;
};
node s={0,1};

二.重载运算符
结构体无法进行+ - * /,==,>,<,>=,<=,!=等运算符操作,需把运算符重载
1.内部实现:
①添加一个参数
此时括号后的const即为第一个参数

struct node{
	int a,b;
	//重载<,返回bool类型 
	bool operator <(const node &x) const{
		if(a==x.a) return b<x.b;
		else return a<x.a;
	}
};

特点:原struct中的成员充当第一个参数
(也可以用this指针指向原结构体成员)

struct node{
	int a,b;
	bool operator <(const node &x) const{
		if(this->a==x.a) return this->b<x.b;
		else return this->a<x.a;
	}
};

②添加两个参数
此时要添加friend关键字

struct node{
	int a,b;
	friend bool operator <(const node &x,const node &y){
		if(x.a==y.a) return x.b<y.b;
		else return x.a<y.a;
	}
};

2.外部实现
传入两个参数,不需要添加friend关键字

struct node{
	int a,b;
};
bool operator <(const node &x,const node &y){
	if(x.a==y.a) return x.b<y.b;
	return x.a<y.a;
}

注意:
1.所有参数类型前均需加上const,表示这个引用指向的对象是常量,不能通过这个引用修改对象的内容。
2.所有参数前均需加上&,表示这是一个引用,而不是一个副本。引用是一个别名,它指向实际的对象,而不是创建一个新的对象。

posted @ 2025-07-10 11:55  Dlyim  阅读(72)  评论(0)    收藏  举报