繁体   English   中英

关于运算符重载的C ++

[英]c++ about operator overloading

为什么

赋值运算符必须是非静态成员函数

operator(),operator []和operator->也必须实现为非静态成员函数。

例如

class IntList
{
private:
    int m_anList[10];

public:
    int& operator[] (const int nIndex);
};

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

这是下标重载。 它只能通过使用成员函数来重载。 不能通过使用朋友功能(例如,

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);
}

所有这些运算符( operator=operator()operator[]operator-> )都会在您将这些运算符定义为非静态成员函数的类的实例上调用!

静态成员或非成员函数类似于自由函数。 它们不会在类的实例上被调用。

例如,如果将operator[]设为静态函数,则内部没有this指针,则该函数将不知道它应作用于哪个实例:

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

它们只有一个参数,因为赋值运算符是二进制运算符。 左侧是要更改的对象,右侧是分配给左侧的对象。

这是非静态的,因为静态成员函数并非特定于该类的单个实例,而是通用于整个类。 除了单个实例之外,对其他任何事情都没有赋值的意义。

赋值运算符(如果我没记错,您是指内部复制构造函数)是实例特定的。 即,每个对象的内容必须是可复制/可复制的。 因此它必须是非静态的。 静态函数具有更大的全局作用,因此无法处理特定实例。 简而言之,如果您需要影响所有实例的功能,则仅必须使用静态成员(变量和方法)。 如在计数器中保存当前可用对象的数量。

现在只需要一个参数-这是因为您需要创建某物的副本(尽管它是内部具有多种数据类型的类对象,但仅是一个对象)

同样,(),[]和->是实例特定的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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