2016-04-29 53 views
0

我可以重载'+'操作符,但我不知道如何为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; 
} 
+0

你需要为你的类重载'operator int'。 – NathanOliver

+1

检查例如[此用户定义的转换参考](http://en.cppreference.com/w/cpp/language/cast_operator)。 –

回答

2

I would like it to be typecasted to any other variable type.

对于任何其他变量类型你需要一个模板用户定义的转换:

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看到默认情况下只产生警告(我记得这是由设计 - 由于大量的遗留代码会破坏),下铛它产生错误:

main.cpp:15:16: error: type 'float' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing] 
     return T{val}; 

和相同的Visual Studio生成错误。

+0

我不确定它是一个非常好的主意,可以在没有约束的情况下对演员操作符进行模板化......这会使错误表达式中的其他简单错误显得虚假。它可以在你不会想到的地方做坏事...... – WhiZTiM

+0

@WhiZTiM我同意,这看起来很诡异 - 我已经添加了'explicit',因此必须使用外部投射 – marcinj