开发者

c++ about operator overloading

why

The assignment operator must be a non-static member function

operator(), operator[], and operator-> must also be implemented as non-static member functions.

for example

class IntList
{
private:
    int m_anList[10];

public:
    int& operator[] 开发者_C百科(const int nIndex);
};

int& IntList::operator[] (const int nIndex)
{
    return m_anList[nIndex];
}

this is subscript overloading. It only can be overloaded by using member function. It cannot be overloaded by using friend function, such as,

class Cents
{
private:
    int m_nCents;

public:
    Cents(int nCents) { m_nCents = nCents; }

    // Overload -cCents
    friend Cents operator-(const Cents &cCents);
};

// note: this function is not a member function!
Cents operator-(const Cents &cCents)
{
    return Cents(-cCents.m_nCents);
}


All these operators (operator=, operator(), operator[], and operator->) gets invoked on an instance of the class of which you define these operators as non-static member functions!

static member or non-member functions are like free functions. They don't get invoked on an instance of the class.

For example, if you make operator[] a static function, then you don't have this pointer inside it, then the function would not know which instance it is supposed to act on:

//illegal code
static int& IntList::operator[] (const int nIndex)
{
    return m_anList[nIndex]; //of which instance this `m_anList` is a member?
}


They have exactly one parameter because the assignment operator is a binary operator. The left hand side is the object being changed, the right hand side is the object being assigned to the left hand side.

It's non-static because static member functions aren't specific to a single instance of that class, they're general to the whole class. It doesn't make sense to do assignment on anything but a single instance.


Assignment operator (If i am not wrong you mean copy constructor internally) is instance specific. I.e. Content of each object must be copied/copyable. So it must be non static. Static functions have a more global role so it cannot take care of specific instances. In short if you have a requirement to affect the functionality of all your instances then only static members (variables and methods) must be used. As in a counter to hold the number of currently available objects count.

Now for only one parameter - It is because you need to create a copy ofsomething (eventhough it is a class object which has multiple data types internally, It is a single object only)

Similarly (),[] and -> are instance specific.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜