如何在我的课堂上实现前后递增/递减运算符? [英] How to implement pre and post-increment / decrement operator in my class?
问题描述
我想重载++
运算符,以便在我的c#类中使用运算符重载使用预递增和后递增.但是只有后增量有效.如何使这两个功能在我的课堂上都能正常工作?
假设我做了一个ABC类-
I want to overload ++
operator to use pre-increment and post-increment using operator overloading in my c# class. But only post-increment is working. How to make both function works in my class?
Suppose I made a class ABC like -
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class ABC
{
public int a,b;
public ABC(int x, int y)
{
a = x;
b = y;
}
public static ABC operator ++(ABC x)
{
x.a++;
x.b++;
return x;
}
}
class Program
{
static void Main(string[] args)
{
ABC a = new ABC(5, 6);
ABC b, c;
b = a++;
Console.WriteLine("After post increment values are {0} and {1} and values of b are {2} and {3}", a.a, a.b, b.a, b.b);// expected output a.a = 6, a.b = 7, b.a = 5, b.b = 6 but not get that
c = ++a;
Console.WriteLine("After pre increment values are {0} and {1} and values of c are {2} and {3}", a.a, a.b, c.a, c.b); // expected output a.a = 7, a.b = 7, c.a = 7, c.b = 8 works fine
Console.Read();
}
}
}
推荐答案
您的示例无法正确实现此一元运算符,如 17.9.1一元运算符中的C#规范所指定:
Your sample fail to implement this unary operator correctly, as specified in the C# specification in 17.9.1 Unary operators :
与C ++不同,此方法不需要 并且事实上,不应修改 其操作数的值直接.
Unlike in C++, this method need not, and, in fact, should not, modify the value of its operand directly.
这是您的一些微单元测试样品:
Here is your sample with some micro unit tests :
using System;
class ABC
{
public int a,b;
public ABC(int x, int y)
{
a = x;
b = y;
}
public static ABC operator ++(ABC x)
{
x.a++;
x.b++;
return x;
}
}
class Program
{
static void Main()
{
var a = new ABC(5, 6);
if ((a.a != 5) || (a.b != 6)) Console.WriteLine(".ctor failed");
var post = a++;
if ((a.a != 6) || (a.b != 7)) Console.WriteLine("post incrementation failed");
if ((post.a != 5) || (post.b != 6)) Console.WriteLine("post incrementation result failed");
var pre = ++a;
if ((a.a != 7) || (a.b != 8)) Console.WriteLine("pre incrementation failed");
if ((pre.a != 7) || (pre.b != 8)) Console.WriteLine("pre incrementation result failed");
Console.Read();
}
}
您的代码失败是后递增结果,原因是您更改了作为参数传递的ABC实例,而不是返回新实例.更正的代码:
Your code fail is the post incrementation result and it is due to the fact that you alter the instance of ABC passed as parameter instead of returning a new instance. Corrected code :
class ABC
{
public int a,b;
public ABC(int x, int y)
{
a = x;
b = y;
}
public static ABC operator ++(ABC x)
{
return new ABC(x.a + 1, x.b + 1);
}
}
这篇关于如何在我的课堂上实现前后递增/递减运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!