我在很长一段时间后刷新 cpp,试图理解运算符重载方法。
我试图重载“operator<<”输出对象的成员。但如果不使用朋友功能我就无法做到这一点。我正在寻找一种不使用友元函数的方法。
这是我的类 def:
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中是否可以。我尝试了一些实现,但都给了我编译错误。请帮助我理解我在这里缺少的一点。
I am refreshing cpp after a long gap, trying to understand the operator overloading methods.
I tried to overload "operator<<" to output members of object. but I am unable to do so without using friend function. I am looking for a method without using friend function.
here is my class def:
class Add{
private:
int x;
public:
friend ostream& operator<<(ostream& ostr, Add const& rhs); //Method 1
void operator<<(ostream& ostr); //Method 2
};
functions implementations
//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;
}
calls from the main function
cout<<Obj_Add; //calls the Method 1
Obj_Add<<cout; //calls the Method 2
Now my question is, I would like to achieve the Method 1 type calls without using the friend function. But do not know, it is possible or not in cpp. I have tried few implementation but all are gives me compile errors. Please help me to understand the point i'm missing here.
发布评论
评论(4)
如果您的类中有公共访问器函数,或者类似
stream
的函数,则不需要与operator<<
建立友谊:v2 具有以下额外优势:允许
stream_to
成为virtual
函数,这对于多态基类很有帮助,因此您不需要重新实现operator<<
对于每一个派生的类,仅stream_to
。If you have public accessor functions in your class, or a
stream
-like one, you don't need the friendship withoperator<<
:v2 has the added benefit of allowing
stream_to
to be avirtual
function, which is helpful for polymorphic base-classes, so you don't need to reimplementoperator<<
for every derived class, onlystream_to
.使用 x 的 getter 是可能的。
如果运算符<<不是好友,无法访问会员x
It's possible with a getter of x.
if the operator<< is not friend, it can not access the member x
如果您有其他方法从对象获取
x
,则可以避免将运算符函数作为友元。You can avoid having the operator function as friend if you have some other means of getting
x
from the object.这是不可能的,除非您添加某种机制来获取
x
,例如public
或不同的机制来打印对象
This is not possible unless you add some mechanism to get
x
out, e.g. apublic
or a different mechanism to print an object