简体   繁体   中英

Where to overload division returning custom class C# operator/ (int,int)

I'm trying to do this:

/// <summary>
/// Syntax support for assigning a new Rational from "x/y" notation.
/// </summary>
/// <param name="num">Numerator, appears before the '/'</param>
/// <param name="denom">Denominator, appears after the '/'</param>
/// <returns>A new Rational using the num/denom convention</returns>
public static Rational operator/(int num,int denom)
{
    Rational r;
    try
    {
        r = new Rational(num, denom);
    }
    catch (Exception e)
    {

        throw e;
    }
    return r;
}

however I get an error when I include it as part of my class, because one of the arguements must be the containing class. I did notice that this works just fine if I declare it outside main() in my test program, however I would like the class file to contain everything so I can hand off the .cs file. Whats the correct way to do this?

Ive also tried

Class Rational
{
     ....
}
public static Rational operator/(...)
{
    ...
}

This does not work because the compiler expects interface,delegate, ... blah blah intellisense keywords.

Thanks for the help!

There is no way to do that. A requirement of a binary operator overload is that one of operands be the type you declaring the operator for. You can't declare operators for other types. The operator you are trying to declare is really for int when you think about it, which already has a division operator.

¶ 7.3.2:

User-defined operator declarations always require at least one of the parameters to be of the class or struct type that contains the operator declaration. Thus, it is not possible for a user-defined operator to have the same signature as a predefined 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM