相关疑难解决方法(0)

可以将重载运算符重构为非成员函数会破坏任何代码吗?

考虑重载加法运算的遗留类模板+=+

template<class T>
class X
{
public:
    X() = default;
    /* implicict */ X(T v): val(v) {}

    X<T>& operator+=(X<T> const& rhs)       { val += rhs.val; return *this; }
    X<T>  operator+ (X<T> const& rhs) const { return X<T>(*this) += rhs;    } 

private:
    T val;
};
Run Code Online (Sandbox Code Playgroud)

在代码审查时,观察到它+是可实现的+=,为什么不使它成为非成员(并保证左右参数的对称性)?

template<class T>
class X
{
public:
    X() = default;
    /* implicit */ X(T v): val(v) {}

    X<T>& operator+=(X<T> const& rhs)       { val += rhs.val; return *this; }

private: …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading implicit-conversion argument-dependent-lookup non-member-functions

9
推荐指数
1
解决办法
208
查看次数

为什么C++标准为std :: bitset :: reference指定了析构函数?

我想知道为什么std::bitset::referencestd::vector<bool>::reference指定一个显式析构函数(不是编译生成的析构函数).因为,例如,boost::dynamic_bitset::reference似乎没有指定这样的析构函数.

c++ destructor reference c++11 std-bitset

5
推荐指数
1
解决办法
181
查看次数