算术运算符

1.只要两个数有一个为long,则结果就为long;没有long时默认为int,即使操作数全为short,byte

13156048-31bf527434e4f749.png

1.png

 

13156048-73537ef869f76a35.png

2.png

 

2.只要两个数有一个为double,则结果就为double;只有两个操作数都为float,结果才为float

 

 

3.++a与a++的区别

13156048-91c401c8cbdf1edb.png

3.png

### 实现算术运算符重载 在多种编程语言中,算术运算符的重载是一种常见的需求。以下是关于如何在 C++ 和 C# 中实现算术运算符重载的具体说明。 #### 在 C++ 中重载算术运算符 C++ 支持通过函数的形式来重载算术运算符。这些运算符可以通过成员函数或非成员函数的方式定义[^1]。下面展示了一个具体的例子: ```cpp class Complex { private: double real; double imag; public: // 构造函数 Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 成员函数形式的加法重载 Complex operator+(const Complex& other) const { return Complex(real + other.real, imag + other.imag); } // 非成员函数形式的加法重载 friend Complex operator-(const Complex& lhs, const Complex& rhs); }; // 定义友元函数用于减法重载 Complex operator-(const Complex& lhs, const Complex& rhs) { return Complex(lhs.real - rhs.real, lhs.imag - rhs.imag); } ``` 上述代码展示了两种方式:一种是在类内部作为成员函数重载 `+` 运算符;另一种是以非成员函数的形式重载 `-` 运算符[^3]。 #### 在 C# 中重载算术运算符 C# 提供了一种简洁的方式来重载算术运算符。开发者可以在类中使用静态方法声明并实现运算符的行为[^2]。以下是一个简单示例: ```csharp using System; public class Point { public int X { get; set; } public int Y { get; set; } public Point(int x, int y) { this.X = x; this.Y = y; } // 加法运算符重载 public static Point operator +(Point p1, Point p2) { return new Point(p1.X + p2.X, p1.Y + p2.Y); } // 减法运算符重载 public static Point operator -(Point p1, Point p2) { return new Point(p1.X - p2.X, p1.Y - p2.Y); } public override string ToString() { return $"({X}, {Y})"; } } class Program { static void Main(string[] args) { Point p1 = new Point(1, 2); Point p2 = new Point(3, 4); Console.WriteLine((p1 + p2).ToString()); // 输出 (4, 6) Console.WriteLine((p1 - p2).ToString()); // 输出 (-2, -2) } } ``` 在这个例子中,`+` 和 `-` 被分别用来处理两个 `Point` 对象相加和相减的操作。 --- #### 总结 无论是 C++ 或者 C#,都提供了灵活的方法支持算术运算符的重载。具体的选择取决于实际的需求以及设计上的考虑因素,比如是否需要访问私有数据成员或者希望保持对称性等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值