在常量方法中调用非常量方法
Calling non const method in const method
#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{};
。
相关文章:
- 为什么常量方法可以采用非常量引用?
- 常量方法中的非常量 lambda 捕获
- Gmock 常量方法不调用,而是调用原始方法
- 为什么我们需要常量方法?
- 模板常量/非常量方法
- 在常量方法中调用非常量方法
- 如何让编译器在C++中更喜欢常量方法重载?
- 常量方法中 decltype 的结果
- 如何从QDialog的常量方法显示QMessageBox?
- 常量方法指针的类型是什么
- C++类的常量方法中将字符数组分配给 T* 的方法
- 在公共常量方法中访问私有成员
- 常量方法中的奇怪行为,其中变量可以修改
- 当函数引用对象(并访问非常量方法)时,如何抛弃常量?
- 非常量指针成员上的C++常量方法
- 从 const 方法调用成员上的非常量方法
- "Reference qualifier correctness"还是应该将非常量方法应用于右值?
- 在Turtle中为常量方法创建Mock
- C++模板来覆盖常量和非常量方法
- 单元测试-在C++TDD中调用重载常量与非常量方法的好方法