我正在编写一个小的Float类,以便更轻松地比较浮点数(正如我们所知,因为浮点数的精度)。所以我需要重新加载几乎所有double的运算符。我发现有太多重复,例如operator+、operator-、operator*和operator/。它们是相似的。所以我使用宏来减少代码长度。但是当我遵守它时,它不起作用。错误是:
happy.cc:24:1: error: pasting "operator" and "+" does not give a valid preprocessing token
happy.cc:25:1: error: pasting "operator" and "-" does not give a valid preprocessing token
happy.cc:26:1: error: pasting "operator" and "*" does not give a valid preprocessing token
happy.cc:27:1: error: pasting "operator" and "/" does not give a valid preprocessing token
这是我的代码:
struct Float
{
typedef double size_type;
static const size_type EPS = 1e-8;
private:
size_type x;
public:
Float(const size_type value = .0): x(value) { }
Float& operator+=(const Float& rhs) { x += rhs.x; return *this; }
Float& operator-=(const Float& rhs) { x -= rhs.x; return *this; }
Float& operator*=(const Float& rhs) { x *= rhs.x; return *this; }
Float& operator/=(const Float& rhs) { x /= rhs.x; return *this; }
};
#define ADD_ARITHMETIC_OPERATOR(x) \
inline const Float operator##x(const Float& lhs, const Float& rhs)\
{\
Float result(lhs);\
return result x##= rhs;\
}
ADD_ARITHMETIC_OPERATOR(+)
ADD_ARITHMETIC_OPERATOR(-)
ADD_ARITHMETIC_OPERATOR(*)
ADD_ARITHMETIC_OPERATOR(/)
我的 g++ 版本是 4.4.3
这是 g++ -E 的结果:
struct Float
{
typedef double size_type;
static const size_type EPS(1e-8);
private:
size_type x;
public:
Float(const size_type value = .0): x(value) { }
Float& operator+=(const Float& rhs) { x += rhs.x; return *this; }
Float& operator-=(const Float& rhs) { x -= rhs.x; return *this; }
Float& operator*=(const Float& rhs) { x *= rhs.x; return *this; }
Float& operator/=(const Float& rhs) { x /= rhs.x; return *this; }
};
inline const Float operator+(const Float& lhs, const Float& rhs){ Float result(lhs); return result += rhs;}
inline const Float operator-(const Float& lhs, const Float& rhs){ Float result(lhs); return result -= rhs;}
inline const Float operator*(const Float& lhs, const Float& rhs){ Float result(lhs); return result *= rhs;}
inline const Float operator/(const Float& lhs, const Float& rhs){ Float result(lhs); return result /= rhs;}