You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C++ const对象的指针成员可调用非const成员函数?

带有指针成员的const对象为何能调用非const成员函数?

先看这段测试代码:

#include <iostream>

struct foo
{
    void func(const int &n)
    {  std::cout << n << std::endl;  }
};

struct test
{
    test() : m_ptr{&m} {}
    
    foo m;
    foo *m_ptr;
};

int main()
{
    test t1;
    const test t2;
    
    t1.m.func(1);
    //t2.m.func(2);   // 编译错误:传递const foo作为this参数丢失限定符
    
    t1.m_ptr->func(10);
    t2.m_ptr->func(20); // 这居然能正常编译?

    // t2.m_ptr = t1.m_ptr;    // 编译错误:只读对象中的成员赋值

    return 0;
}

问题核心:const修饰的是指针本身,而非指针指向的对象

当声明const test t2时,C++会将t2的所有成员视为const属性,但指针成员的const规则和普通成员有区别:

  • 对普通成员t2.m:t2是const对象,所以t2.m的类型是const foo。而foo::func()是非const成员函数,它要求调用对象(即this指针)为foo*类型,但const foo只能转换为const foo*,类型不匹配,因此触发编译错误。
  • 对指针成员t2.m_ptr:t2是const对象,所以m_ptr的类型变为foo* const——意思是指针本身是只读的,不能修改它指向的地址,但指针指向的对象仍然是foo类型(非const)。因此通过t2.m_ptr->func()调用时,传递的this指针是foo*,完全符合func()的要求,所以能正常编译。

为什么添加成员函数返回m_ptr后调用会报错?

如果给test添加一个返回const foo*的const成员函数,比如:

struct test
{
    // ... 其他成员
    const foo* get_ptr() const { return m_ptr; }
};

此时t2.get_ptr()返回的是const foo*,用这个指针调用func()时,this指针需要是foo*,但const foo*无法隐式转换为foo*,就会触发和t2.m.func(2)一样的编译错误。

如果成员函数返回的是foo*而非const foo*,那调用依然能正常通过——你遇到的报错情况,应该是成员函数返回了指向const对象的指针或引用导致的。

内容的提问来源于stack exchange,提问作者j4x

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:10:54