c++ - 强制转换是可覆盖的操作吗?如果是这样,如何?

标签 c++ casting overriding

是否可以在 C++ 中覆盖(C 风格的)转换?

假设我有代码

double x = 42;
int k = (int)x;

我可以让第二行的类型转换执行我写的一些代码吗?有点像

// I don't know C++
// I have no idea if this has more syntax errors than words
operator (int)(double) {
    std::cout << "casting from double to int" << std::endl;
}

我问的原因是因为问题 "Is there any way to get gcc or clang to warn on explicit casts?"以及我的建议。

最佳答案

§ 12.3.1/1 "Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions and are used for implicit type conversions (Clause 4), for initialization (8.5), and for explicit type conversions (5.4, 5.2.9)."

是的,我们可以进行转换,但前提是一侧或两侧是用户定义的类型,所以我们不能将 double 转换为 int

struct demostruct {
    demostruct(int x) :data(x) {} //used for conversions from int to demostruct
    operator int() {return data;} //used for conversions from demostruct to int
    int data;
};

int main(int argc, char** argv) {
    demostruct ds = argc; //conversion from int to demostruct
    return ds; //conversion from demostruct to int
}

正如 Robᵩ 指出的那样,您可以将 explicit 关键字添加到这些转换函数中的任何一个,这需要用户使用 (demostruct)argc(int)ds 就像在您的代码中一样,而不是让它们隐式转换。如果您与同一类型相互转换,通常最好将其中一个或两个都设为 explicit,否则您可能会遇到编译错误。

关于c++ - 强制转换是可覆盖的操作吗?如果是这样,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10320282/

相关文章:

c# - 为什么我应该用 "unchecked"明确包围?

Java 继承和转换

比较 int 和 size_t

spring - 实现 BeanPostProcessor spring 5 + java 9

c++ - 相同的未更改代码是否可能有时运行有时不运行?

C++ 链表,堆栈(某种)

c++ - 生命周期短的分配会导致堆碎片吗?

c++ - 使用 mac os 在 OpenCv 中迭代大量图像的问题

scala - 如何访问 Scala 中的 "overridden"内部类?

c++ - 调用虚函数的覆盖导致段错误