[英]Typecast overloading
我可以重载'+'运算符,但不确定如何为NewType进行类型转换。 我希望将其转换为其他任何变量类型。 您能提供一些建议吗? 非常感谢!
#include <iostream>
class NewType {
private:
float val;
public:
NewType(float v) { val = v; }
friend NewType operator+(const NewType &c1, const NewType &c2);
float GetVal() const { return val; }
};
NewType operator+(const NewType &c1, const NewType &c2) { return NewType(c1.val + c2.val); }
int main() {
NewType a = 13.7;
// Here is the problem, I would like this to print 13.
std::cout << (int) a << std::endl;
return 0;
}
我希望将其转换为其他任何变量类型。
对于任何其他变量类型,您需要模板化的用户定义转换:
class NewType {
public
// ...
template<typename T>
explicit operator T() const { return T(val); }
// ...
};
explicit
(此处为C ++ 11及更高版本)可确保您将使用显式强制转换,即:
NewType a = 13.7;
int n = a; // compile error
int n2 = static_cast<int>(a); // now OK
您还可以在用户定义的转换运算符中使用统一初始化:
template<typename T>
explicit operator T() const { return T{val}; }
如果您的演员表可能需要缩小,这将给您额外的警告。 但是,正如我在gcc下看到的那样,默认情况下仅生成警告(我记得这是设计使然-由于许多旧代码会中断),在clang下会生成错误:
main.cpp:15:16: error: type 'float' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing]
return T{val};
并且相同的Visual Studio会产生错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.