在常量方法中调用非常量方法

Calling non const method in const method

本文关键字:常量 方法 非常 调用      更新时间:2023-10-16
#include <iostream>
#include <memory>
class B
{
public:
B(){}
void g() { }
};
class A
{
public:
A()
{
ptr_ = std::make_shared<B>();  
}
void f() const 
{
ptr_->g(); // compile
//obj_.g(); // doesn't compile as expected
}
std::shared_ptr<B> ptr_;
B obj_;
};
int main()
{
A a;
a.f();
}

我很惊讶这段代码构建得很好。在 A::f(( 中,我调用数据成员的非常量方法。当此数据成员是它构建的指针时,如果它不是指针,则不会按预期构建,因为 B::g(( 是非常量。

你明白为什么我能够在常量函数内调用非常量函数吗?

关键是谁在const成员函数中const指针?

尖?在const成员函数f中,ptr_,即指针本身被认为是const,而不是它所指向的对象。你在 pointee 上调用非常量成员函数g,那就没问题了。

此外,你不能像ptr_ = std::make_shared<B>();一样ptr_指针本身(与obj_相同(上执行任何修改(并调用非常量成员函数(;但你可以对它指向的对象执行此操作,如*ptr_ = B{};