当前位置:网站首页>C#入门系列(三十一) -- 运算符重载
C#入门系列(三十一) -- 运算符重载
2022-07-26 08:33:00 【InfoQ】
//修饰符 返回值类型 operator 可重载的运算符(参数列表)
public static Student operator +(Student a, Student b)
{
//方法体;
}
可重载和不可重载运算符
代码示例
using System;
namespace _6_2_1运算符重载
{
class Program
{
static void Main(string[] args)
{
Student st1 = new Student();
Student st2 = new Student();
Student st3 = new Student();
st1._acore = 40;
st2._acore = 50;
Console.WriteLine("st1和st2成绩是否相同:" + (st1 == st2));
Console.WriteLine("st1和st2成绩是否相同:" + (st1 != st2));
Console.WriteLine("运算前成绩:{0},{1},{2}", st1._acore, st2._acore, st3._acore);
//对象相加
st3 = st1 + st2;
//编译器自动重载+=
st1 += st2;
Console.WriteLine("运算后成绩:{0},{1},{2}",st1._acore,st2._acore,st3._acore);
Console.ReadKey();
}
}
class Student
{
private int acore;
public int _acore {
get { return acore; }
set { acore = value; }
}
//+重载: 对象加法,求得学生成绩和
public static Student operator +(Student b, Student c)
{
Student stu = new Student();
stu.acore = b.acore + c.acore;
return stu;
}
//当重载==时,必须重载!=,否则编译报错
public static bool operator ==(Student b , Student c)
{
bool result = false;
if(b.acore == c.acore)
{
result = true;
}
return result;
}
public static bool operator !=(Student b, Student c)
{
bool result = false;
if (b.acore != c.acore)
{
result = true;
}
return result;
}
}
}

边栏推荐
- 利用模m的原根存在性判断以及求解
- Vscode utility shortcut
- 2022-7-4 personal qualifying 1 competition experience
- 【加密周报】加密市场有所回温?寒冬仍未解冻 盘点上周加密市场发生的重大事件
- Excel delete blank lines
- Mysql8 dual master and dual slave +mycat2 read / write separation
- Beauty naked chat for a while, naked chat over the crematorium!
- P1825 [USACO11OPEN]Corn Maze S
- QSS add resource file of QT
- 2022-7-6 personal qualifying 3 competition experience
猜你喜欢
Excel delete blank lines
Xshell batch send command to multiple sessions
Foundry教程:使用多种方式编写可升级的智能合约(上)
Mycat2 deploy master-slave MariaDB
QT uses QSS to make a beautiful login interface (hand-in-hand teaching)
Super nice navigation page (static page)
Using the primitive root of module m to judge and solve
有限元学习知识点备案
为什么要在时钟输出上预留电容的工位?
Lesson 3: gcc compiler
随机推荐
Vscode domestic image server acceleration
OSPF summary
Apple's tough new rule: third-party payment also requires a percentage, and developers lose a lot!
[abstract base class inheritance, DOM, event - learning summary]
Random distribution learning notes
【加密周报】加密市场有所回温?寒冬仍未解冻 盘点上周加密市场发生的重大事件
23.9 application exit application exit
Spark SQL common date functions
Redis进阶
Regular expression job
Basic configuration of BGP
Flutter compilation fails
Kotlin program control
The data read by Flink Oracle CDC is always null. Do you know
Winter vacation homework & Stamp cutting
Kotlin function
23.6 23.7 web environment web environment variable reading
Excel delete blank lines
QT note 1
Storage of drawings (refined version)