c++ passing a const object reference to a function

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

error: passing 'const QByteArray' as 'this' argument of 'QByteArray& QByteArray::append(const QByteArray&)' discards qualifiers [-fpermissive]

since it is a convention to make objects const while passing as function arguments i have done it. but now i am getting an error!!, i dnt want to make the function constant as i have to convert data in qbyte array into short and then append it another array.

QByteArray ba((const char*)m_output.data(), sizeof(ushort));     playbackBuffer.append(ba); 

I really need to pass this array into playbackbuffer;
It is giving me an error on playbackBuffer.append(ba);

please help
thanks in advance

回答1:

This means you are calling a non-const member function on a const member. Presumably, your append function modifies the byte array. With a const reference, you shouldn't be modifying.



回答2:

Basically what it says is that you're trying to append to a constant array.

If "append" does not change the object itself but just returns the two arrays appended, the method needs to be declared const to allow the call.



回答3:

Consider this:

struct foo {     void bar(); };  const foo f; f.bar(); 

Here, in the call to bar(), the this pointer is &f. But bar() is not a const-function, so the type of this is foo*, which is incompatible with const foo*. (In other words, bar() says it might mutate the foo, but f says it's a non-mutablefoo.)

Either bar() needs to be marked as const (if it can), or f needs to not be const.

In your case, I'm going to assume you're using Qt and so cannot modify QByteArray (nor should you, since append is necessarily a non-const function), and instead suggest you get rid of the const on the object, which is preventing you from using the function.



回答4:

So you are trying to call a non const function on a const object? That's what passing a const xxx as 'this' argument would mean. Since ultimately any member function really is (Class * this, rest of arguments)



回答5:

Either make your

QByteArray& QByteArray::append(const QByteArray&); 

be

QByteArray& QByteArray::append(const QByteArray&) const; 

(highly unlikely to solve anything) or just

    QByteArray* pObj = const_cast(&your_obj)     if (pObj)         pObj->append(... 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!