Overloading assignment operator in a class template that can cast to another template type

前端 未结 2 2066
一向
一向 2020-12-16 05:18
#ifndef NUMBER_HPP
#define NUMBER_HPP

template 
class Number
{
public:
  Number( T value ) : m_value( value )
  {
  }

  T value() const
  {
    retu         


        
2条回答
  •  清酒与你
    2020-12-16 05:42

    You have some of the Ts in the wrong place. It should be

    template 
    Number& operator=( const Number& number )
    {
        m_value = number.value();
        return *this;
    }
    

    This will let you do

    Integer a(4);
    Float b(6.2f);
    
    a = b;
    
    cout << a.value() << endl;
    

    and it will print 6, a behaviour similar to that of the int and float types you are imitating.

提交回复
热议问题