c++ error: passing ‘const xxx’ as ‘this’ argument discards qualifiers

本文介绍了C++中const对象只能调用const成员函数的规则,解释了为什么const引用不能直接用于非const成员函数,以及如何正确使用const_cast处理这种情况。还讨论了比较函数的const限定和编程习惯。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在C++中,const对象只能调用const成员函数。

c++在类的成员函数实现中会隐式传入一个指向当前对象的this指针。有如下示例类

struct Resolution {
  int width = 0;
  int height = 0;

  bool operator!=(const Resolution &b) {
    return width != b.width || height != b.height;
  }

  void Print() {
    std::cout << "width " << width << ", height " << height << std::endl;
  }
};

int main() {

  const Resolution r720p{.width = 1280, .height = 720};
  r720p.Print();

  Resolution r1080p{.width = 1920, .height = 1080};
  r1080p.Print();

  return 0;
}

会出现如下问题

 error: passing ‘const Resolution’ as ‘this’ argument discards qualifiers [-fpermissive]
   21 |   r720p.Print();
      |   ~~~~~~~~~~~^~

实际的Resolution::Print函数应该是这样的void print(Resolution* this);,这代表一个指向Resolution对象的指针this被传入到了Print函数中。

如果是const Resolution 则会传递const Resolution* this, 但const 指针是不能直接传给非const指针的。除非使用const_cast。很显然这种自己调用过程没法去添加const_cast.

所以只需要记住结论:

1.  C++中const 引用的是对象时只能访问该对象的const 函数,因为其他函数有可能会修改该对象的成员,编译器为了避免该类事情发生,会认为调用非const函数是错误的。

2. 在一个加了const限定符的成员函数中,不能够调用非const成员函数。

写一个比较函数

bool Compare(const Resolution &a, const Resolution &b) { return a != b; }

则也要求必须是const 的比较实现方式

  bool operator!=(const Resolution &b) const {
    return width != b.width || height != b.height;
  }

有时候其实会忘记这种结论,那么可以用另一种习惯性方式去解决,不用定义成员比较函数,直接定义全局比较函数。

bool operator==(const Resolution &a, const Resolution &b) {
  return a.width != b.width && a.height != b.height;
}

 这种无论r720p, r1080p是不是const都可以直接比较了。

所以这也就有一种编程习惯——如果不改变成员变量的成员函数的一般最好都加上const后缀。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值