I overload a operator for the Communicater
class like this:
…
friend bool Communicater::operator << (Communicater c, char a); //重载<<
…
bool operator << (Communicater c, char a){
…
return true;
}
…
*communicater << “override test2”;
…
But when I call it, I found that a socket inside the
Communicater
class unespectingly closed right after the call.
With further debug, I believe its because the WSACleanup()
which is in the deconstructor of that class executed and further more close the socket.
I think it’s because using formal parameters Communicater c
like this bool operator<<(Communicater c, char *a)
will actually bring a copy of the actual parameter, passed with pointer *communicater
, which is previously in the heap, into the stack. After calling the function, the copy in the stack deconstructs which clean up all WSA data. ==This is different from Java.==That’s why the socket will be closed unespectingly.
At last, by changing the function into friend bool Communicater::operator << (Communicater &c, char *a);
which simply reference the object instead of copying it. Problem solved.
2017/3/15 16:10
Later I found that wrong.
In order to make sure continous operator use works the same, I tried just change it to
friend Communicater Communicater::operator << (Communicater &c, char *a);
and get the same error which that the Communicater &c
is still destructed even if it suppose to be working. ==Not sure why.====(Now I get it. It’s still copied…2017/3/15 18:32)==
I tried friend Communicater* Communicater::operator << (Communicater &c, char *a);
but this way won’t work either because I need to overwrite for another scenario which is Communicater operator << (Communicater &c, char *a);
.
At last, I change it to friend Communicater &Communicater::operator << (Communicater &c, char *a);
so that it finally works…
2017/3/15 16:30