4

隔了很长一段时间后,我正在刷新 cpp,试图了解运算符重载方法。我试图重载“operator<<”以输出对象的成员。但如果不使用朋友功能,我就无法这样做。我正在寻找一种不使用朋友功能的方法。

这是我的班级定义:

class Add{
private:
int x;

public:
friend ostream& operator<<(ostream& ostr, Add const& rhs); //Method 1
void operator<<(ostream& ostr);                //Method 2
};

功能实现

//Method 1
ostream& operator<<(ostream &ostr, Add const& rhs)
{
    ostr<<rhs.x;

return ostr;
}

//Method 2
void Add::operator<<(ostream& ostr)
{
    cout<<" using operator<< \n";
    ostr<<x;
}

从主函数调用

cout<<Obj_Add;  //calls the Method 1

Obj_Add<<cout;  //calls the Method 2

现在我的问题是,我想在不使用朋友功能的情况下实现方法 1 类型的调用。但不知道,有没有可能在cpp中。我尝试了很少的实现,但都给了我编译错误。请帮助我理解我在这里遗漏的一点。

4

4 回答 4

5

如果您的班级中有公共访问器功能,或者类似的功能stream,则不需要与以下的友谊operator<<

// v1
class foo{
public:
  int data() const{ return _data; }
private:
  int _data;
};

std::ostream& operator<<(std::ostream& o, foo const& f){
  return o << f.data();
}

// v2
class foo{
public:
  void stream_to(std::ostream& o){
    o << _data;
  }
private:
  int _data;
};

std::ostream& operator<<(std::ostream& o, foo const& f){
  f.stream_to(o);
  return o;
}

v2 具有允许stream_to成为virtual函数的额外好处,这对多态基类很有帮助,因此您不需要operator<<为每个派生类重新实现,只需stream_to.

于 2012-01-11T12:33:38.000 回答
2

使用 x 的吸气剂是可能的。

如果 operator<< 不是朋友,则无法访问成员 x

class Add {
    private:
        int x;

    public:
        int getX() { return x; }
};

//Method 1
ostream& operator<<(ostream &ostr, Add const& rhs)
{
    //ostr<<rhs.x;       //Fail: x is private

    ostr << rhs.getX();  //Good

    return ostr;
}
于 2012-01-11T12:40:08.917 回答
1

x如果您有其他一些从对象获取的方法,您可以避免让操作员充当朋友。

class Foo
{
private:
    int bar;

public:
    int get_bar() const { return bar; }
};

ostream &operator<<(ostream &os, const Foo &foo)
{
    os << foo.get_bar();
    return os;
}
于 2012-01-11T12:36:25.783 回答
0

这是不可能的,除非您添加一些机制来x退出,例如public

// in the class
int get_x() const { return x; }

或打印对象的不同机制

// outside the class
std::ostream &operator<<(std::ostream &out, Add const &obj)
{
    obj.print(out);
    return out;
}
于 2012-01-11T12:34:26.857 回答