【问题标题】:C++ << operator overloading without friend functionC++ << 没有友元函数的运算符重载
【发布时间】:2016-09-09 10:02:40
【问题描述】:

正如主题所说。有可能这样做吗?我能够通过重载“+”运算符来实现这一点,但是,我无法使用“

这是一个适用于我的朋友功能的代码示例:

class Punkt2D
{
    int x,y;

    public:
        Punkt2D(int wartoscX, int wartoscY) : x(wartoscX), y(wartoscY) {}
        friend ostream& operator<<(ostream& out, Punkt2D& punkt);
};

ostream& operator<<(ostream& out, Punkt2D& punkt)
{
    out << "(" << punkt.x << ", " << punkt.y << ")" << endl; 
    return out;
}

int main()
{
    Punkt2D p1(10,15);

    cout << p1 << endl;
    return 0;
}

我在 '+' 上尝试了此代码,但没有与该函数成为朋友。其他运营商也可以吗?也许这是一个愚蠢的问题,但是我对 C++ 很陌生,找不到任何关于该主题的资源:(

class Vector
{
    public:

    double dx, dy;
    Vector() {dx=0; dy=0;}
    Vector(double x, double y) 
    {
        cout << "Podaj x " << endl;
        cin >>x;
        cout << "Podaj y " << endl;
        cin >> y;
        dx = x; dy = y;

    }
    Vector operator+ (Vector v);
};


Vector Vector::operator+ (Vector v)
{
    Vector tmpVector;
    tmpVector.dx = dx +v.dx;
    tmpVector.dy = dy+ v.dy;
    return tmpVector;
}

int main()
{
    double d,e;

    Vector a(d,e);
    Vector b(d,e);
    Vector c;
    c = a +b;
    cout<<endl << c.dy << " " << c.dx;
    return 0;
}

【问题讨论】:

    标签: c++ overloading operator-keyword


    【解决方案1】:

    只要函数只调用类的public成员函数(或访问public数据成员,如果有的话)它不需要是朋友。

    您的Vector 示例仅访问public 成员,因此它有效。

    您的Punkt2D 正在访问private 成员,因此运营商需要成为朋友。

    【讨论】:

    • 好吧,我有点困惑,因为答案似乎是矛盾的。如果类的所有成员都是公共的,那么在不与函数交朋友的情况下,代码行会是什么样子?我只对带有 ostream 元素的行感兴趣,即函数的声明和定义。
    • 在类声明之后以std::ostream&amp; operator&lt;&lt;(std:: ostream&amp; out, const Punkt2D&amp; punkt) 形式声明即可,因为它不是类的成员(例如在头文件中)。 operator&lt;&lt;() 的定义(即实现)(它需要在某个地方,但不需要在标题中,除非它被内联)然后需要避免访问类的privateprotected members
    • 谢谢彼得 :)
    【解决方案2】:

    需要成为好友才能访问私有成员。

    Vector 中,成员是公开的,因此不同。

    【讨论】:

      【解决方案3】:

      流操作符:

      operator << output
      operator >> input
      

      当您将它们用作流运算符(而不是二进制移位)时,第一个参数是流。由于您无权访问流对象(它不是您可以修改的),因此它们不能是成员运算符,它们必须在类外部。因此,他们必须要么是班级的朋友,要么有权访问将为您进行流式传输的公共方法。

      【讨论】:

        猜你喜欢
        • 2011-03-19
        • 2016-01-24
        • 1970-01-01
        • 1970-01-01
        • 2016-04-14
        • 2017-07-26
        • 2011-08-25
        • 1970-01-01
        • 2011-04-28
        相关资源
        最近更新 更多