1

I was reading about const_cast operator in c++

1.First weird thing thing i can't understand is

const_cast operator syntax i.e.

-const_cast--<--Type-->--(--expression--)--------------------><

what i have understand about this syntax is that it helps to cast away constness of anexpressionof type Type .But consider this code

class  ConstTest {   

private:
    int year;
public:
    ConstTest() : year(2007) {}
    void  printYear() const;
};

int main() {
    ConstTest c;
    c.printYear();
    return  0;
}

void ConstTest::printYear() const {
    ConstTest  *c  = const_cast<ConstTest*>(this);
    c->year  = 42;
    std::cout  <<  "This  is the  year "  << year  << std::endl;
}

Here in line ConstTest *c = const_cast<ConstTest*>(this), I think that the const of this pointer should be cast away, but the output shows that it is the object which this refers to that loses its const-ness.

I feel that the code should have been ConstTest *c = const_cast<ConstTest>(*this), but this produces an error. I know i am wrong at many interpretations. Please correct them all.

2.my second problem is the statement given below

The result of a const_cast expression is an rvalue unless Type is a reference type. In this case, the result is an lvalue.

Why is this so, and why it is not true in case of pointers?

4

1 に答える 1

4

Type型の式の恒常性を捨てるのに役立ちます

いいえ、Typeは結果のタイプであり、オペランドのタイプではありません。

私が思うに、このポインタの定数は捨てるべきです

thisタイプがありconst ConstTest*ます。const_cast<ConstTest*>(this)タイプがありConstTest*ます。これが、constへのポインタから「constをキャストする」という意味です。

コードはそうあるべきだったと思いますConstTest *c = const_cast<ConstTest>(*this)

の結果const_cast<T>はタイプTであり、それが定義されています。おそらくあなたはそれを別の方法で定義したでしょうが、幸運なことに、あなたはConstTest*書くconst_cast<ConstTest>ことによってそれを得るのではなく、書くことによってそれを得るのconst_cast<ConstTest*>です。好みの構文は利用できません。

あなたはするかConstTest &c = const_cast<ConstTest&>(*this)、することができるConstTest *c = const_cast<ConstTest*>(this)ので、あなたの好きなものを選んでください。

Typeが参照型でない限り、const_cast式の結果は右辺値です。この場合、結果は左辺値になります。

なぜそうなのか、そしてなぜそれがポインタの場合には当てはまらないのか?

ポインタについても同様です。ConstTest*は参照型ではなく、の結果const_cast<ConstTest*>(this)は右辺値です。次に、その値を変数に割り当てますc

于 2012-02-03T17:00:05.613 に答える