我可以重載'+'操作符,但我不知道如何爲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)。 –