简体   繁体   English

C ++-ostream(<<)重载

[英]C++ - ostream (<<) overloading

I was wondering if there is any way to overload the << operator for a class without declaring it as a friend function. 我想知道是否有任何方法可以将类的<<运算符重载而不将其声明为朋友函数。 My professor said this is the only way to do it, but I wanted to know if there is another way that he was unaware of. 我的教授说,这是唯一的方法,但是我想知道他是否不知道还有另一种方法。

只要您希望通过类的公共接口访问要输出的所有内容,就无需使operator <<函数成为该类的朋友。

Yes, you can 是的你可以

std::ostream& operator<<(std::ostream &stream, WHATEVER_TYPE var) {
    std::string str = somehowstringify(var);
    return stream << str;
}

Note however that by virtue of it being a non-member non-friend function it can of course only access the public interface of std::ostream , this usually isn't a problem. 但是请注意,由于它是非成员非朋友功能,因此它当然只能访问std::ostream的公共接口,这通常不是问题。

Yes, one way to do it is like this: 是的,一种方法是这样的:

class Node
{
public:
    // other parts of the class here
    std::ostream& put(std::ostream& out) const { return out << n; };
private:
   int n;
};

std::ostream& operator<<(std::ostream& out, const Node& node) {
    return node.put(out);
}

You need to declare it is as friend function if and only if you need access to it's private members . 仅当您需要访问它的私有成员时,才需要将其声明为朋友功能
You can always do this without using friend function if: 在以下情况下,您始终可以在不使用好友功能的情况下执行此操作:
1) No private member access is required. 1)不需要私人成员访问。
2) You provide a mechanism to access your private member otherwise. 2)您提供了一种以其他方式访问您的私人成员的机制。 eg 例如

class foo
{
    int myValue;
    public:
    int getValue()
    {
        return myValue;
    }
}

As R Sahu has pointed out, the requirement is that the operator should be able to access everything it has to display. 正如R Sahu所指出的那样,要求是操作员应该能够访问其必须显示的所有内容。

Here are a few possible options 这里有一些可能的选择

1.Adding the overloaded function as a friend function 1,将重载函数添加为好友函数

2.Making all the required data members of the class accessible for the function using either public accessor methods or public data members 2使用公共访问器方法或公共数据成员使该函数可以访问该类的所有必需数据成员

class MyClass {
   private:
   int a;
   int b;
   int c;
   public:
   MyClass(int x,int y,int z):a(x),b(y),c(z) {};
   MyClass():a(0),b(0),c(0) {};
   int geta() { return a; }
   int getb() { return b; }
   int getc() { return c; }
};

std::ostream& operator<<(std::ostream &ostr,MyClass &myclass) {
   ostr << myclass.geta()<<" - " << myclass.getb() << " - " << myclass.getc() ;
   return ostr;
}


int main (int argc, char const* argv[])
{
   MyClass A(4,5,6);
   cout << A <<endl;

        return 0;
}

3.Add a public helper function , say output with the signature std::ostream& output(std::ostream& str) and use it later in the operator function. 3.添加一个公共帮助程序函数,例如output带有签名std::ostream& output(std::ostream& str) ,然后在运算符函数中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM