无法访问C ++ std :: set中对象的非const成员函数 [英] Unable to access non-const member functions of objects in C++ std::set

查看:149
本文介绍了无法访问C ++ std :: set中对象的非const成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

消息是我制作的课程。我在main函数中有一组它们传递给messageTimeOut(以及其他一些函数)。在使用itorator的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对象的非const成员函数,但是我该如何使它成为非const的Message对象所以我可以访问非const成员函数并更改消息?谢谢

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中对象的非const成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆