chaoren00001
chaoren00001
2019-01-28 01:02

为什么const_cast对基本类型常量不起作用,但是对自定义的类对象和结构体实例的常量却有用?

  • c++

如果我定义了const int n、const aClass c、const aStruct s,那么为什么const_cast可以作用于c和s,但是却不能作用于n呢?

如下列代码举的例子:

class C {
public:
    int cval;
    C(int c) :cval(c){ }
};
struct S {
    int sval;
};
int main() {
    const int n = 6666;
    const C c(666);
    const S s{ 66 };
    cout << "int, class and structure variables begin with:\n";
    cout << "n, c.cval, s.sval = " << n << ", " << c.cval << ", " << s.sval << endl;
    // const_cast 用于指针
    int *n2 = const_cast<int*>(&n);
    C *c2 = const_cast<C*>(&c);
    S *s2 = const_cast<S*>(&s);
    // const_cast 用于引用
    int &n3 = const_cast<int&>(n);
    C &c3 = const_cast<C&>(c);
    S &s3 = const_cast<S&>(s);

    *n2 = 2000;
    c2->cval = 200;
    s2->sval = 20;
    cout << "\nafter const_cast on pointers:\n";
    cout << "n, c.cval, s.sval = " << n << ", " << c.cval << ", " << s.sval << endl;

    n3 = 3000;
    c3.cval = 300;
    s3.sval = 30;
    cout << "\nafter const_cast on reference:\n";
    cout << "n, c.cval, s.sval = " << n << ", " << c.cval << ", " << s.sval << endl;
    return 0;
}

运行结果:

图片说明

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答