passing ‘const this argument discards qualifiers [-fpermissive]

一世执手 提交于 2019-12-18 12:06:20

问题


I have a class Cache which has a function write specified as

bool write(const MemoryAccess &memory_access, CacheLine &cl);

I am calling this function like this.

const Cache *this_cache;
c = (a==b)?my_cache:not_cache;
c->write(memory_access,cl);

The above line is giving me following error

"passing ‘const Cache’ as ‘this’ argument of ‘bool Cache::write(const MemoryAccess&, CacheLine&)’ discards qualifiers [-fpermissive]."

the this argument is compiler specific which helps in code-mangling and breaking local namespace variable priority. But such a variable is not being passed here.


回答1:


Since c is of type const Cache *, you can only call const member functions on it.

You have two options:

(1) remove const from the declaration of c;

(2) change Cache::write() like so:

 bool write(const MemoryAccess &memory_access, CacheLine &cl) const;

(Note the added const at the end.)




回答2:


When you call a method via a pointer to an object, this object is implicitly passed to the method as this pointer. c probably has type const Cache*. Since method write is not declared as const, it has non-const this pointer accessible from its body requiring const qualifier of c to be discarded.




回答3:


Also if your class's method returns pointer on any member you shouldn't forget write const before returning type example:

const float * getPosition() const{...}



来源:https://stackoverflow.com/questions/10765787/passing-const-this-argument-discards-qualifiers-fpermissive

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