I didn't get any errors. I'm just wondering. Why it doesn't work when I typed "no4.Print();". did not class already create?
I was learning operator overloading. i noticed that it only works when i use Console.WriteLine func. If i tried to use Print function inside the class it errors.
using System;
class Number{
private int myNumber;
public Number(int myNumber){
this.myNumber=myNumber;
}
public static Number operator *(Number a, Number b){
return new Number(a.myNumber*b.myNumber);
}
public void Print(){
Console.WriteLine(this.myNumber);
}
public static implicit operator int(Number a) {
return a.myNumber;
}
public static implicit operator Number(int a) {
return new Number(a);
}
}
class HelloWorld {
static void Main() {
Number no1 = new Number(5);
Number no2 = new Number(2);
Number no3 = no1*no2;
no3.Print();
int no4 = new Number(1312);
Console.WriteLine(no4); //It doesnt work no4.Print();
Number no5 = 2121;
no5.Print();
}
}
You can't call no4.Print();
because the int
type/class does not have such a method. Also, nobody is telling the variable to get converted to a Number
object. However, when you write something like
((Number)no4).Print();
you are explicitly converting your int
value to a Number
object with the help of your defined implicit operator Number(int a)
operator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.