Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

c++ - Why must C# operator overloads be static?

Why does C# require operator overloads to be static methods rather than member functions (like C++)? (Perhaps more specifically: what was the design motivation for this decision?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Answered in excruciating detail here:

http://blogs.msdn.com/ericlippert/archive/2007/05/14/why-are-overloaded-operators-always-static-in-c.aspx

There is also another subtler point about value types and instance operators. Static operators make this kind of code possible:

class Blah {

    int m_iVal;

    public static Blah operator+ (Blah l, int intVal)
    {
        if(l == null)
            l = new Blah();
        l.m_iVal += intVal;
        return l;
    }
}

//main
Blah b = null;
b = b + 5;

So you can invoke the operator, even though the reference is null. This wouldn't be the case for instance operators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...