gpt4 book ai didi

C# -- 我们可以将重载运算符称为 ClassName.operator+(p1, p2) 吗?

转载 作者:行者123 更新时间:2023-12-03 21:50:17 25 4
gpt4 key购买 nike

鉴于以下代码,我尝试实现

public static Point operator +(int x, Point p1)

通过重用

public static Point operator +(Point p1, int x)

但它不起作用。我们真的不能在 C# 中做到这一点吗?

谢谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Point
{
public int X { get; set; }
public int Y { get; set; }

public Point() { }
public Point(int x, int y)
{
X = x;
Y = y;
}

public override string ToString()
{
return string.Format("x: {0}, y: {1}", X, 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, int x)
{
return new Point(p1.X+x, p1.Y+x);
}

public static Point operator +(int x, Point p1)
{
return Point.operator+(p1, x); // **doesn't compile**
}

}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point(1, 2);
Point p2 = new Point { X = 3, Y = 4 };

Console.WriteLine("p1: {0}", p2);
Console.WriteLine("p2: {0}", p1);

Console.WriteLine("p1+p2: {0}", p1+p2);

Console.WriteLine("p1+10: {0}", p1 + 10);
Console.WriteLine("p1+10: {0}", 10 + p1);
Console.ReadLine();
}
}
}

//更新了编译器错误//

Error   1   Invalid expression term 'operator'  C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  37  26  ConsoleApplication2
Error 2 Identifier expected; 'operator' is a keyword C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 26 ConsoleApplication2
Error 3 Invalid expression term ',' C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 38 ConsoleApplication2
Error 4 ) expected C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 38 ConsoleApplication2
Error 5 ; expected C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 40 ConsoleApplication2
Error 6 Invalid expression term ')' C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 41 ConsoleApplication2
Error 7 ; expected C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs 37 41 ConsoleApplication2

最佳答案

您当然可以重用该运算符,就像这样:

public static Point operator +(int x, Point p1)
{
return p1 + x;
}

但是没有语法可以像方法一样显式调用运算符。

关于C# -- 我们可以将重载运算符称为 ClassName.operator+(p1, p2) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6036932/

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