我可以重载'+'操作符,但我不知道如何为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;
}
你需要为你的类重载'operator int'。 – NathanOliver
检查例如[此用户定义的转换参考](http://en.cppreference.com/w/cpp/language/cast_operator)。 –