gpt4 book ai didi

c++ - 定义您自己的显式转换

转载 作者:搜寻专家 更新时间:2023-10-31 00:45:13 25 4
gpt4 key购买 nike

假设,如果无法通过显式转换(例如 static_cast)从一种类型转换为另一种类型,是否可以为其定义显式转换运算符?

编辑:

我正在寻找一种方法来为以下内容定义显式转换运算符:

class SmallInt {

public:

// The Default Constructor
SmallInt(int i = 0): val(i) {
if (i < 0 || i > 255)
throw std::out_of_range("Bad SmallInt initializer");
}

// Conversion Operator
operator int() const {
return val;
}

private:
std::size_t val;

};

int main()
{
SmallInt si(100);

int i = si; // here, I want an explicit conversion.
}

最佳答案

对于用户定义的类型,您可以定义 type cast operator .运算符的语法是

operator <return-type>()

您还应该知道,隐式类型转换运算符通常不受欢迎,因为它们可能会给编译器留下太多余地并导致意外行为。相反,您应该在类中定义 to_someType() 成员函数来执行类型转换。


对此不确定,但我相信 C++0x 允许您指定类型转换为 explicit 以防止隐式类型转换。

关于c++ - 定义您自己的显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7251653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com