15-struct(构造函数,重载)

必须充分掌握struct的使用,包括其构造和重载函数的写法:

#include <iostream>
using namespace std;

struct node {
	int x, y;
	node(){ 
		
	}
//	node (int x, int y){
//		this->x = x;
//		this->y = y;
//	}
	node (int x, int y) : x(x), y(y){
		
	}
	node operator + (const node s){
		node rt;
		rt.x = this->x + s.x;
		rt.y = this->y + s.y;
		return rt;
	}
	node operator * (const node s){
		node rt;
		rt.x = this->x * s.x;
		rt.y = this->y * s.y;
		return rt;
	}
	bool operator ==(const node s){
		if(s.x == this->x && s.y == this->y){
			return 1;
		}
		else{
			return 0;
		}
	}
	bool operator < (const node s){
		if(this->x < s.x){
			return 1;
		} 
		else{
			return 0;
		}
	}
}; 

int main(){
	node a, b;
	a.x = a.y = 1;
	b.x = b.y = 3;
	a = a + b;
	cout << "a: " << a.x  << " " << a.y << endl;
	node c(1, 3);
	cout << "c: " << c.x << " " << c.y << endl;
	node d = c;
	cout << "d: " << d.x << " " << d.y << endl;
	if(d == c){
		cout << "d = c" << endl;
	}
	if(a < c){
		cout << "a < c" << endl;
	} 
	else{
		cout << "a !< c" << endl;
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/8681729.html