简体   繁体   中英

c++ passing a const object reference to a function

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

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.

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.

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-mutable foo .)

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.

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)

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<QByteArray*>(&your_obj)
    if (pObj)
        pObj->append(...

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