[英]When using static cast, does it make more sense to cast as class type or object reference?
I just realized that I can use either to achieve the same effect. 我只是意识到我可以使用任一方法来达到相同的效果。 Are there any caveats?
有什么警告吗? Which convention makes more sense?
哪种约定更有意义?
#include <iostream>
using namespace std;
class some_class {
public:
void echo() {
cout << 1 << endl;
}
};
class other_class : public some_class {
public:
void echo() {
// Does it matter?
static_cast<some_class>(*this).echo();
static_cast<some_class&>(*this).echo();
}
};
int main() {
other_class a;
a.echo();
return 0;
}
The first cast creates a temporary object of type some_class
, initialized from *this
by slicing, then calls echo
on the temporary object, then destroys the temporary object. 第一个
some_class
会创建一个some_class
类型的临时对象,该对象通过切片从*this
初始化,然后在该临时对象上调用echo
,然后销毁该临时对象。 If you made the echo
function update a member variable of some_class
, you would notice that *this
actually did not get updated. 如果您使
echo
函数update为some_class
的成员变量,您会注意到*this
实际上没有被更新。
The second cast calls some_class::echo();
第二个转换调用
some_class::echo();
function on the *this
object, without creating anything. 函数在
*this
对象上,而不创建任何对象。
Typically the second option is what you are aiming for. 通常,第二种选择是您要针对的目标。 As noted by davidhigh in comments, it is a cleaner code style (IMHO anyway) to simply write
some_class::echo();
正如davidhigh在评论中指出的那样,简单地编写
some_class::echo();
是一种更简洁的代码样式(无论如何还是恕我直言some_class::echo();
instead of using the cast. 而不是使用演员表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.