通过const方法在成员上调用nonconst方法 [英] Invoking a nonconst method on a member from a const method

查看:104
本文介绍了通过const方法在成员上调用nonconst方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶地发现这种常量"性的漏洞":

I was surprised to find this "hole" in "const"ness:

#include <stdio.h>

class A
{
  int r ;
public:
  A():r(0){}

  void nonconst()
  {
    puts( "I am in ur nonconst method" ) ;
    r++;
  }
} ;

class B
{
  A a ;
  A* aPtr ;

public:
  B(){ aPtr = new A() ; }

  void go() const
  {
    //a.nonconst() ;      // illegal
    aPtr->nonconst() ;  //legal
  }
} ;

int main()
{
  B b ;
  b.go() ;
}

因此基本上,如果指针引用了类型为A的对象,则可以从const方法B::go()中调用非常量成员函数(适当地命名为nonconst()).

So basically from const method B::go(), you can invoke the non-const member function (aptly named nonconst()) if object of type A is referenced by a pointer.

那是为什么?似乎是一个问题(在我的代码中找到了它).

Why is that? Seems like a problem (it kind of was in my code, where I found it.)

推荐答案

当类型为B的对象为const时,则其所有成员均为const,这意味着在B::go()期间其两个成员均为const. ,有效

When and object of type B is const, then all of its members are const, which means its two members are, for the duration of B::go(), effectively

A const a;
A * const aPtr;

第一个是类型为A的常量对象,在该对象上只能调用const成员函数.但是,第二个是指向非恒定A的恒定指针.您不能从函数B::go()中合法地说出aPtr = <anything>,因为那样会修改aPtr,它是恒定的.

The first is a constant object of type A, on which you can only call const member functions. The second, however, is a constant pointer to a non-constant A. You could not legally say aPtr = <anything> from within the function B::go(), since that would modify aPtr, which is constant.

指向常量A的指针将声明为A const* aPtrconst A* aPtr,这将使调用非常量A::nonconst()非法.

A pointer to a constant A would be declared as A const* aPtr or const A* aPtr, which would then make calling the non-constant A::nonconst() illegal.

这篇关于通过const方法在成员上调用nonconst方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆