C++ 如何使用 const_cast?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19554841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use const_cast?
提问by Sarah
I have a private variable in my Student
class defined as:
我的类中有一个私有变量Student
定义为:
const int studentNumnber;
I am trying to write a copy constructor for the Student
and I need to cast away the constness to do this. Unfortunately, I don't understand how to use std::const_cast
.
我正在尝试为 编写一个复制构造函数Student
,我需要抛弃常量性来做到这一点。不幸的是,我不明白如何使用std::const_cast
.
This is what I am trying to do in my copy constructor:
这就是我在复制构造函数中尝试执行的操作:
Student(const Student & s)
: Person(p.getName(), p.getEmailAddress(), p.getBirthDate()), school(0), studentNumber(0) {
school = new char[strlen(s.school) + 1];
strcpy_s(school, strlen(s.school) + 1, s.school);
const_cast<int*>(this)->studentNumber = s.studentNumber;
//studentNumber = s.studentNumber);
}
That doesn't work... I am unsure of the syntax.
那不起作用......我不确定语法。
回答by timrau
You are not allowed to const_cast
variables that are actually const
. This results in undefined behavior. const_cast
is used to remove the const-ness from references and pointers that ultimately refer to something that is not const
.
不允许您使用const_cast
实际上是const
. 这会导致未定义的行为。const_cast
用于从最终引用不是const
.
So, this is allowed:
所以,这是允许的:
int i = 0;
const int& ref = i;
const int* ptr = &i;
const_cast<int&>(ref) = 3;
*const_cast<int*>(ptr) = 3;
It's allowed because i
, the object being assigned to, is not const
. The below is not allowed:
这是允许的,因为i
被分配给的对象不是const
。以下是不允许的:
const int i = 0;
const int& ref = i;
const int* ptr = &i;
const_cast<int&>(ref) = 3;
*const_cast<int*>(ptr) = 3;
because here i
is const
and you are modifying it by assigning it a new value. The code will compile, but its behavior is undefined (which can mean anything from "it works just fine" to "the program will crash".)
因为这里i
是const
并且您正在通过为其分配一个新值来修改它。代码会编译,但它的行为是未定义的(这可能意味着从“它工作得很好”到“程序会崩溃”。)
You should initialize constant data members in the constructor's initializers instead of assigning them in the body of constructors:
您应该在构造函数的初始值设定项中初始化常量数据成员,而不是在构造函数的主体中分配它们:
Student(const Student & s)
: Person(p.getName(), p.getEmailAddress(), p.getBirthDate()),
school(0),
studentNumber(s.studentNumber)
{
// ...
}
回答by Ravi Podugu
In your code you are trying cast this pointer instead of variable. You can try the following:
在您的代码中,您正在尝试转换此指针而不是变量。您可以尝试以下操作:
Student(const Student & s)
: Person(p.getName(), p.getEmailAddress(), p.getBirthDate()), school(0), studentNumber(0) {
school = new char[strlen(s.school) + 1];
strcpy_s(school, strlen(s.school) + 1, s.school);
*const_cast<int*>(&studentNumber) = s.studentNumber;
}