简体   繁体   中英

how to use use properly in std:ostream& member, while “this” is a const?

I have a class named "Subscriber" , which is inherited from a class named "Client", which contains the following lines of code , in "protected" :

std::ostream& messagesSink;

std::ostream&  getMessagesSink() {
    return messagesSink;
}

(messagesSink is initialized in the constructor of Subscribers)

and there is the following function-member in "subscriber" :

virtual void recieveMessage(const std::string& message ,
        const Topic& topic,
        const Client& client) const {
    messagesSink << "Topic: "<< topic
            << ". Sender: #" << client.getId() << ". Reciver: #"
            << getId() << ".Message: " << message;
}

the problem goes like this:in his current state, the code has no compilation errors, but if I replace the use of the member messagesSink in the function getMessagesSink(), as the code below, compilation errors appears:

virtual void recieveMessage(const std::string& message ,
        const Topic& topic,
        const Client& client) const {
    getMessagesSink() << "Topic: "<< topic
            << ". Sender: #" << client.getId() << ". Reciver: #"
            << getId() << ".Message: " << message;
}

my questions are:

1) what is the diffrence between before and after?

2) how to use properly the refrence to std::ostream ,while in a function that keeps "this" as a const?

The problem is that getMessagesSink is not marked const . receiveMessage is marked const so it can't call non-const member functions.

You cannot use non-const member functions inside const member functions of the same object. As far as the compiler is concerned you could be modifying the object when you call getMessagesSink().

I think getMessagesSink() should be const, if you cannot change that and you still want your function to be const you can do something like this inside receiveMessage().

Subscriber* self = const_cast<Subscriber*>(this);
std::ostream& messageSink = self->getMessagesSink();

Otherwise you have to either make your function non-const, or simply use the protected messagesSink object directly. Of course if the implementation of getMessageSink() changes, doing something to the std::ostream before returning a reference to it your code would likely break, or at least stop working as intended.

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