跳到正文

个人记录

构造函数与运算符重载

mini_plus约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年4月12日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 1 分钟
获赞
1

版本

  1. v1当前
C++
#include<iostream>
#include<cstdio>
using namespace std;
struct room{
	int stu,score,avg;
	//构造函数
	room(int a,int b){
		stu=a;
		score=b;
		avg=score/stu;
	} 
	//运算符重载
	room operator+(room other) const{
		room c(stu+other.stu,score+other.score);
		return c;
	} 
	room operator*(int k) const{
		room c(stu*k,score*k);
		return c;
	}
	bool operator>(room other) const{
		if(stu!=other.stu){
			return stu>other.stu;
		}
		return score>other.score;
	}
};
int main(){
	room a(10,1000);
	cout<<a.avg<<endl;
	room b(10,800);
	room c=a+b;
	cout<<a.avg<<endl;
	room d=c*3;
	cout<<d.stu<<endl;
	if(a>b){
		cout<<"a>b"<<endl;
	}
}
原文