static_cast< const A>(* this)和static_cast< const A&>(* this) [英] difference between static_cast<const A>(*this) and static_cast<const A&>(*this)

查看:553
本文介绍了static_cast< const A>(* this)和static_cast< const A&>(* this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中(取自有效的C ++):

in the following code ( taken from effective C++ ):

class A 
{
  ....
  ....
  ....

char& operator[](std::size_t position)         // now just calls const op[]
  {
    return
      const_cast<char&>(                         // cast away const on

                                                 // op[]'s return type;

        static_cast<const TextBlock&>(*this)     // add const to *this's type;

          [position]                            // call const version of op[]

      );
  }

  const char& operator[](int index) const
  {
     ...
     ...
     ...
  }
}
//complete example, tested with VC 2010
#include<iostream>
#include<string>

class TextBlock
{
public:
    TextBlock(std::string st):text(st){};
    TextBlock(char* cstr): text(cstr){};
    TextBlock(const TextBlock& r)
    {
        std::cout<<"copy constructor called"<<std::endl;
    }
    char& operator[](int index)
    {
        std::cout<<"non-const operator"<<std::endl;
        return const_cast<char&>(static_cast<const TextBlock>(*this)[index]);
    }

    const char& operator[](int index) const
    {
        std::cout<<"const operator"<<std::endl;
        return text[index];
    }

private:
    std::string text;
};

int main()
{
    TextBlock rt("hello");
    std::cout<<rt[0]<<std::endl;
}



在这段代码中,如果你改变static_cast从const TextBlock&到const TextBlock,这导致非const版本的operator []被递归调用。任何人都可以解释这背后的原因是什么(为什么const TextBlock导致不调用const成员函数operator [])。

In this code, if you change the static_cast from const TextBlock& to const TextBlock, this results in non-const version of operator[] getting called recursively. Can anyone explain what's the reason behind this ( why const TextBlock results in not calling const member function operator[] ).

推荐答案

原因是因为

const A a();

A b();

是不同的对象,在CPP中,非常量对象不能调用常量函数,反之亦然;因此,您需要为const和非const对象分别声明两次相同的函数。

are different objects, and in CPP non-constant objects cannot call constant functions and vice versa; therefore, you need the same function to be declared twice for a const and non-const object respectively.

cout << a[0] << endl;

是合法的,但

cout << b[0] << endl;

不是。
因为这个原因,你应该为非const对象重载[]运算符。为了避免复制代码,作者建议使用const对象的函数通过抛弃它的constness。因此,您可以:

is not. For that reason you should overload [] operator for non-const object. In order to avoid copying the code, author suggest using a function for const object through casting away its constness. For that reason you get:

char& operator[](std::size_t position)
{
     return const_cast <char &>( static_cast <const A &>(*this) [position] );
}

换句话说,你只需将对象转换为const

in other words, you just convert your object to const

char& operator[](std::size_t position)
{
     const A temp = *this;      //create a const object 
                                    //and assign current object to it
     ....
}

尝试使用const obj的[]运算符

try to use []operator of const obj

char& operator[](std::size_t position)
{
     const A temp = *this;      //create a const object 
                                    //and assign current object to it
     return temp[position];     // call an overloaded operator [] 
                                // of the const function
}

得到一个错误,因为[] const函数的运算符返回const char&并且此函数返回char& amp。

get an error because []operator of const function returns const char& and this function returns char&. Thus cast constness away

char& operator[](std::size_t position)
{
     const A temp = *this;      //create a const object 
                                //and assign current object to it
     return const_cast <char &>( temp[position] );
 }

现在完成了。问题是:如何

Now you are done. The question is: "How

const A temp = *this;
return const_cast <char &> (temp[position]);

成为:

return const_cast <char &> ( static_cast <const A &> (*this)[position]);

?原因是当你使用temp - 你将非const的隐式转换为const对象,因此你可以替换:

? The reason for that is when you are using temp - you are making implicit cast of non-const to a const object, thus you can replace:

const A temp = *this;                                // implicit cast

const A temp = static_cast <const A &> (*this)        //explicit  

这也适用于:

const A temp = const_cast <const A &> (*this) 

,因为您可以进行显式转换 - 您不再需要临时表空间,因此:

and since you can make an explicit cast - you don't need a temp anymore, thus:

return const_cast <char &> (static_cast <const A &>(*this)[position]);

这将返回一个非const引用到这个const类型对象的char,正确的原因,你不能使用

this will return a non-const ref to a char from this const-casted object that calls an overloaded operator[] :) Exactly for that reason you cannot use

return const_cast <char &> ((*this)[position]);

因为这是一个非常量对象;因此,它将使它调用不成本函数(重载operator []),这将导致无限递归。

because this is a not-const object; therefore, it will make it to call not cost function (to overload operator[]) which will cause an infinite recursion.

希望它有意义。

这篇关于static_cast&lt; const A&gt;(* this)和static_cast&lt; const A&amp;&gt;(* this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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