2

假设,如果通过显式转换无法从一种类型转换另一种类型,例如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.
}
4

3 回答 3

3

对于用户定义的类型,您可以定义类型转换运算符。运算符的语法是

operator <return-type>()

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


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

于 2011-08-31T01:36:12.477 回答
2

在当前标准中,不能标记从您的类型到不同类型的转换explicit,这在某种程度上是有意义的:如果您想显式转换,您始终可以提供一个实现转换的函数:

struct small_int {
   int value();
};
small_int si(10);
int i = si.value();   // explicit in some sense, cannot be implicitly converted

再说一次,它可能没有多大意义因为在即将发布的标准中,如果您的编译器支持它,您可以将转换运算符标记为explicit

struct small_int {
   explicit operator int();
};
small_int si(10);
// int i = si;                 // error
int i = (int)si;               // ok: explicit conversion
int j = static_cast<int>(si);  // ok: explicit conversion
于 2011-08-31T07:41:21.877 回答
0

如果这是您想要的,您可以定义转换运算符,例如:

void foo (bool b) {}

struct S {
   operator bool () {return true;} // convert to a bool
};

int main () {
   S s;
   foo (s);  // call the operator bool.
}

尽管它不是真正推荐的,因为一旦定义,这种隐式转换可能会发生在您意想不到的尴尬地方。

于 2011-08-31T01:34:28.677 回答