gpt4 book ai didi

c# - 为什么++运算符重载时++foo和foo++没有区别?

转载 作者:太空狗 更新时间:2023-10-30 01:22:30 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Post-increment Operator Overloading
Why are Postfix ++/— categorized as primary Operators in C#?

我看到我可以重载 ++-- 运算符。通常您通过两种方式使用这些运算符。前后递增/递减一个int示例:

int b = 2; 
//if i write this
Console.WriteLine(++b); //it outputs 3
//or if i write this
Console.WriteLine(b++); //outpusts 2

但是当涉及到运算符重载时,情况有点不同:

    class Fly
{
private string Status { get; set; }

public Fly()
{
Status = "landed";
}

public override string ToString()
{
return "This fly is " + Status;
}

public static Fly operator ++(Fly fly)
{
fly.Status = "flying";
return fly;
}
}


static void Main(string[] args)
{
Fly foo = new Fly();

Console.WriteLine(foo++); //outputs flying and should be landed
//why do these 2 output the same?
Console.WriteLine(++foo); //outputs flying
}

我的问题是为什么最后这两行输出相同的东西?更具体地说,为什么(两行中的)第一行输出 flying


解决方案是将运算符重载更改为:

        public static Fly operator ++(Fly fly)
{
Fly result = new Fly {Status = "flying"};
return result;
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com