简体   繁体   中英

Error when Overloading the operator <<

_3DTocka operator<<(ostream& os, _3DTocka _3D){
    cout << "(" << _3D.x << "," << _3D.y << "," << _3D.z << ")" << endl;
}

The above is my code and it gives an error: it must take exactly one argument (1 line)

_3DTocka is the name of the class..

Three problems: First you're declaring the function wrong, it should return the ostream reference it receives as the first argument. Then it doesn't use that ostream argument, but is hardcoded to cout . Thirdly it doesn't return anything, which will lead to undefined behavior .

Regarding your actual compilation error, you're most likely defining the function as a member function in the class. An output operator defined as a class member is something completely different from an output operator defined as a stand-alone function: When declared as a member function it should take one argument, and it's a value to output to the object . If it's a stand-alone function (or defined as friend inside the class) then it's for outputting the object passed as the second argument "to" the object passed as the first argument.


Regarding the errors:

friend ostream& operator<<(ostream& os, _3DTocka _3D) {
    return os << '(' << _3D.x << ',' << _3D.y << ',' << _3D.z << ')';
}

A few notes: * I have made the string literals into character literals. Handling strings is more work than handling a single character * I now use the provided output stream, which means that you can use this for any kind of output stream (like files) * I have removed the endl , it's not needed and should be provided by the "caller" of this function.

Now you can do

_3DTocka o = ...;

cout << o << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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