隔了很长一段时间后,我正在刷新 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中。我尝试了很少的实现,但都给了我编译错误。请帮助我理解我在这里遗漏的一点。