我来自C ++,并且以C#作为新手,只需尝试一下:
class Class1
{
int mI = 0;
string mS = "ab";
public static Class1 operator + (Class1 obj1, Class1 obj2)
{
return new Class1()
{
mI = obj1.mI + obj2.mI,
mS = obj1.mS + obj2.mS
};
}
public static void operator += (Class1 obj1)
{
mI += obj1.mI;
mS += obj1.mS;
}
}
我发现operator+=
函数没有编译,说:
错误CS1019:应重载一元运算符。
那么C#根本不执行这种运算符重载吗?
答案 0 :(得分:8)
您可以像per the documentation那样重载### try to use a set ###
mport random
import math
something = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
correct_word = something[random.randint(0, len(something) - 1)]
correct_s = set()
left = 100
for s in correct_word:
correct_s.add(s)
gusses = len(correct_word) * 2#math.ceil(len(correct_word)/2)
space = "_ "
win = False
guss = set()
blob = ""
for i in range(len(correct_word)):
blob += "_ "
print(blob + "GUESS LEFT: " + str(gusses))
while not win:
gus = input("ENTER A LETTER: ")
left = 0
if gus in correct_s:
#correct_s.remove(gus)
now = ""
for l in correct_word:
guss.add(gus)
if l in guss:
now += l + " "
else:
now += "_ "
left += 1
print("GREAT!")
else:
gusses -= 1
now = ""
for l in correct_word:
if l in guss:
now += l + " "
else:
now += "_ "
left += 1
print("OOPS!")
print(now + "GUESS LEFT: " + str(gusses))
if left == 0:
print("CONGRATULATIONS, YOU WIN!")
win = True
if gusses <= 0:
print("SORRY, YOU ARE OUT OF GUSSES!")
print("THE RIGHT WORD IS: " + correct_word)
break
,但不能重载+
:
赋值运算符不能显式重载。但是,当您重载二进制运算符时,相应的赋值运算符(如果有)也会隐式重载。例如,
+=
是使用+=
求值的,该值可以重载。
因此,如您所见,+
被认为是+=
。这就是为什么不允许重载x = x + y
运算符的原因。