C ++如何编写一个不是成员函数的运算符?

时间:2011-07-10 04:34:50

标签: c++

任何人都知道如何为不属于该类成员函数的类编写运算符?

4 个答案:

答案 0 :(得分:2)

只需将其设为免费功能或朋友功能即可。一个很好的例子是operator<<

class X {
    public:
    int x; 
}

ostream& operator<< (ostream& os, const X& x) {
    os << x.x;
    return os;
}

使其成为朋友功能的好处是您可以直接访问私人成员,而免费功能必须通过公共方法访问所有成员。

答案 1 :(得分:1)

算术operator,流operator s,等等通常不是类的成员。但是,他们可能需要成为朋友才能访问private数据成员。

我不想使用friend并公开可以由operator使用的方法。我相信这更符合Open/closed principle,因为我可以轻松添加减法运算符而无需编辑类。

这些对于单元测试也很方便(例如,我可以“注入”std::ostringstream来测试print()的输出。

以下是一个例子:

#include <iostream>

class Number
{
public:
    Number(int j)
        :i(j)
    {
    }

    void print(std::ostream& os) const
    {
        os << i;
    }

    int value() const
    {
        return i;
    }
private:
    int i;
};

std::ostream& operator <<(std::ostream& os, const Number& n)
{
    n.print(os);
    return os;
}

Number operator +(const Number& n, const Number& o)
{
    return Number(n.value() + o.value());
}

int main()
{
    Number a(4), b(5), c(a + b);
    std::cerr << c << std::endl;
}

答案 2 :(得分:0)

只需使用运营商名称声明全局函数:

Point operator+(Point& p, Vector& v) {
    return new Point(p.x + q.i, p.y + q.j);
}

答案 3 :(得分:0)

基本上,您可以将操作符移出类,并将参数添加到参数列表的开头。在许多情况下,您还需要将操作员函数声明为朋友。

例如

class Foo
{
    Foo operator +( Foo const& other );
};

变为

class Foo
{
    friend Foo operator +( Foo const&, Foo const& );
};

Foo operator +( Foo const& first, Foo const& second );

friend语句允许运营商仍然访问所需的任何私人或受保护成员。

请注意,以这种方式可以对哪些运算符进行重载存在一些限制。有关此类列表,请参阅this article