Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在const方法中调用非const方法 #包括 #包括 B类 { 公众: B(){} void g(){} }; 甲级 { 公众: () { ptr_u=std::使_共享(); } void f()常量 { ptr_ug->g();//编译 //obj_ug.g();//未按预期编译 } std::共享ptr ptr; B obj_; }; int main() { A A; a、 f(); }_C++ - Fatal编程技术网

C++ 在const方法中调用非const方法 #包括 #包括 B类 { 公众: B(){} void g(){} }; 甲级 { 公众: () { ptr_u=std::使_共享(); } void f()常量 { ptr_ug->g();//编译 //obj_ug.g();//未按预期编译 } std::共享ptr ptr; B obj_; }; int main() { A A; a、 f(); }

C++ 在const方法中调用非const方法 #包括 #包括 B类 { 公众: B(){} void g(){} }; 甲级 { 公众: () { ptr_u=std::使_共享(); } void f()常量 { ptr_ug->g();//编译 //obj_ug.g();//未按预期编译 } std::共享ptr ptr; B obj_; }; int main() { A A; a、 f(); },c++,C++,我很惊讶这段代码构建得很好。在A::f()中,我调用数据成员的非常量方法。当此数据成员是它生成的指针时,如果它不是指针,则不会按预期生成,因为B::g()是非常量 你明白为什么我可以在常量函数中调用非常量函数吗?关键是谁是const成员函数中的const,指针?那个尖头 在const成员函数f,ptr,即指针本身被视为const,而不是它指向的对象。在指针对象上调用非常量成员函数g,这样就可以了 此外,您不能对指针ptr_本身(与obj_相同)执行任何修改(并调用非常量成员函数),如ptr=st

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


你明白为什么我可以在常量函数中调用非常量函数吗?

关键是谁是
const
成员函数中的
const
,指针?那个尖头

const
成员函数
f
ptr
,即指针本身被视为
const
,而不是它指向的对象。在指针对象上调用非常量成员函数
g
,这样就可以了


此外,您不能对指针
ptr_
本身(与
obj_
相同)执行任何修改(并调用非常量成员函数),如
ptr=std::make_shared();但是您可以在它所指向的对象上执行此操作,如
*ptr\ub{}

为什么不能?调用另一个类的非常量方法。
#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();
}