传递'const这个参数丢弃限定符[-fpermissive]

pra*_*kar 38 gcc g++

我有一个类Cache,其函数写入指定为

bool write(const MemoryAccess &memory_access, CacheLine &cl);
Run Code Online (Sandbox Code Playgroud)

我这样称呼这个函数.

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

以上行给出了以下错误

"将'const Cache'作为'bool Cache :: write(const MemoryAccess&,CacheLine&)'的'this'参数传递'丢弃限定符[-fpermissive]."

这个参数是特定于编译器的,它有助于代码修改和破坏本地命名空间变量优先级.但这样的变量并没有在这里传递.

NPE*_*NPE 46

由于c是类型const Cache *,您只能const在其上调用成员函数.

您有两种选择:

(1)const从声明中删除c;

(2)改变Cache::write()如下:

 bool write(const MemoryAccess &memory_access, CacheLine &cl) const;
Run Code Online (Sandbox Code Playgroud)

(注意最后添加const.)

  • 签名结束时const的意义是什么?当我们说这是不变的时,我们究竟是什么意思.它应该默认不变吗? (3认同)
  • @prathmesh.kallurkar:http://www.parashift.com/c++-faq-lite/const- Correctness.html#faq-18.10 (2认同)

Ale*_*lin 5

当您通过指向对象的指针调用方法时,该对象将作为this指针隐式传递给该方法。c可能有类型const Cache*。由于方法write未声明为const,因此它具有this可从其主体访问的非常量指针,需要丢弃const限定符 of c