问题描述
Message 是我做的一个类.我在传递给 messageTimeOut(和其他一些函数)的主函数中有一组它们.在使用迭代器的 messageTimeOut 中,我循环遍历它们并访问不同的成员函数.但是,我只能访问迭代器指向的 Message 的 const 成员函数.如果我尝试访问非 const 成员函数,则会出现错误:
Message is a class I made. I have a set of them in the main function that I pass to messageTimeOut (and some other functions). In messageTimeOut using an itorator I am looping through them and accessing different member functions. However, I can only access const member functions of the Message pointed to by the iterator. If I try to access non const member functions I get the error:
在函数‘void messageTimeOut(threadParameters*)’中:main.cpp:74:33: 错误:将const Message"作为this"参数传递'void Message::setTimedOut(bool)' 丢弃限定符 [-fpermissive]."
"In function 'void messageTimeOut(threadParameters*)': main.cpp:74:33: error: passing 'const Message' as 'this' argument of 'void Message::setTimedOut(bool)' discards qualifiers [-fpermissive]."
我无法访问 const Message 对象的非常量成员函数是有道理的,但是我如何使它成为非常量 Message 对象,以便我可以访问非常量成员函数并更改消息?谢谢
It makes sense that I cannot access a non-const member function of a const Message object, but how do I go about making this a non const Message object so I can access non const member functions and change the Message? Thanks
我的部分代码:
[ . . . ]
void messageTimeOut( threadParameters* params )
{
set<Message>::iterator it = params->messages->begin();
[ . . . ]
for ( ; it != params->messages->end(); ++it )
{
if ( (it->createdTime() + RESPONSE_WAIT) < GetTickCount() )
{
it->setTimedOut(true); // error
}
}
ReleaseMutex(sentQueueMutex);
}
[ . . . ]
int main()
{
threadParameters rmparameters;
set<Message> sentMessages;
[ . . . ]
rmparameters.logFile = &logFile;
rmparameters.socket = socketDesciptor;
rmparameters.messages = &sentMessages;
[ . . . ]
messageTimeOut( rmparameters );
[ . . . ]
return 0;
}
推荐答案
你不能.
std::set 中的元素总是常量,否则用户可以通过修改属于集合的元素来修改集合中的排序.
Elements inside an std::set are always constant, because otherwise an user could modifiy the ordering in the set by modifying an element which belong to the set.
请注意,您调用的函数不会更改顺序并不重要,因为 std::set 无法检查这一点.
Notice that it doesn't matter that the function that you invoke doesn't change the ordering, since std::set has no way to check this.
解决这个问题的常用方法是从集合中删除元素,修改它,然后重新插入它.另一种方法是使用地图,即使这可能会迫使您复制一些数据.
A common way to fix this is to remove the element from the set, modify it, then reinsert it. Another way would be to use a map, even if this would probably force you to duplicate some data.
这篇关于无法访问 C++ std::set 中对象的非常量成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!