문제

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.

도움이 되었습니까?

해결책 2

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.
2) You provide a mechanism to access your private member otherwise. e.g.

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

다른 팁

There is no need to make the operator<< function a friend of the class as long as everything you want to be output is accessible through the public interface of the class.

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.

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);
}

As R Sahu has pointed out, the requirement is that the operator should be able to access everything it has to display.

Here are a few possible options

1.Adding the overloaded function as a friend function

2.Making all the required data members of the class accessible for the function using either public accessor methods or public data members

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top