C++ 定义类型转换

标签 c++ casting

有没有一种方法可以定义从用户定义类到原始类型(int、short 等)的类型转换?此外,任何此类机制是否需要显式转换,还是隐式工作?

例如:

// simplified example class
class MyNumberClass
{
private:
    int value;
public:
    // allows for implicit type casting/promotion from int to MyNumberClass
    MyNumberClass(const int &v)
    {
        value = v;
    }
};
// defined already above
MyNumberClass t = 5;

// What's the method definition required to overload this?
int b = t; // implicit cast, b=5.
// What's the method definition required to overload this?
int c = (int) t; // C-style explicit cast, c=5.
// ... etc. for other cast types such as dynamic_cast, const_cast, etc.

最佳答案

是的,您可以定义一个 operator type() 来进行转换,是的,只要需要这样的转换,它就会隐式地工作:

operator int() {
  return value;
}

关于C++ 定义类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824278/

相关文章:

c++ - CUDA 内核 "Only a single pack parameter is allowed"解决方法?

c++ - 有人可以解释如何在模板中使用 result_of 吗?

PHP字符串到整数玩得不好,编码问题?

java - 类型转换和包装: some strange cases

c++ - GNU C 内联汇编中的输入操作数 `"m"(var )` and Output Operand ` "=m"(var)` ?不使用任何指令作为屏障?

c++ - 使用虚函数调用时节省堆栈空间

c++ - 编译 C++,Makefile 基础知识 : variables, 包括库

swift - For-in 循环和类型转换仅适用于匹配类型的对象

c# - 使用延迟加载的 NHibernate ObjectProxy 转换

c# - 如何从对象列表中获取特定类型的对象