[英]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" : 我有一个名为“Subscriber”的类,它继承自名为“Client”的类,其中包含以下代码行,位于“protected”中:
std::ostream& messagesSink;
std::ostream& getMessagesSink() {
return messagesSink;
}
(messagesSink is initialized in the constructor of Subscribers) (messagesSink在订阅者的构造函数中初始化)
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: 问题是这样的:在他当前的状态下,代码没有编译错误,但如果我在函数getMessagesSink()中替换成员messagesSink的使用,如下面的代码,则出现编译错误:
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? 1)之前和之后的差异是什么?
2) how to use properly the refrence to std::ostream ,while in a function that keeps "this" as a const? 2)如何正确使用对std :: ostream的引用,而在一个将“this”保持为const的函数中?
The problem is that getMessagesSink
is not marked const
. 问题是getMessagesSink
没有标记为const
。 receiveMessage
is marked const
so it can't call non-const member functions. receiveMessage
标记为const
因此无法调用非const成员函数。
You cannot use non-const member functions inside const member functions of the same object. 您不能在同一对象的const成员函数内使用非const成员函数。 As far as the compiler is concerned you could be modifying the object when you call getMessagesSink(). 就编译器而言,您可以在调用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(). 我认为getMessagesSink()应该是const,如果你不能改变它,你仍然希望你的函数是const,你可以在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. 否则,您必须使您的函数非常量,或者直接使用受保护的messagesSink对象。 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. 当然,如果getMessageSink()的实现发生了变化,在返回对它的引用之前对std :: ostream做了一些事情,你的代码可能会中断,或者至少停止按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.