我可以重载 operator= 以将 class 的对象分配给另一个 class 的变量但是两个 class 都来自同一个 class 模板
Could I overload operator= to assign object of a class to a variable of another class but both class are from the same class template
比如我有一个class
template<class T>
class Number
{
private:
T number;
public:
Number(T num)
{
number=num;
}
void operator=(T num)
{
number=num;
}
}
如何重载赋值运算符以将 Number 对象分配给 Number 类型的变量,或者使用同一模板的另一种类型的参数专门化一种类型的方法?顺便说一句,是否可以将 class 模板 Number 的别名设为 "MyChar",这样我就不需要再使用 class 名称 Number但是别名 MyChar
使赋值运算符成为具有单独类型参数的模板成员函数:
// Make sure the template on U can access private number
template <class U> friend class Number;
template<class U>
Number<T>& operator=(const Number<U>& num)
{
number = static_cast<T>(num.number);
return *this;
}
比如我有一个class
template<class T>
class Number
{
private:
T number;
public:
Number(T num)
{
number=num;
}
void operator=(T num)
{
number=num;
}
}
如何重载赋值运算符以将 Number
使赋值运算符成为具有单独类型参数的模板成员函数:
// Make sure the template on U can access private number
template <class U> friend class Number;
template<class U>
Number<T>& operator=(const Number<U>& num)
{
number = static_cast<T>(num.number);
return *this;
}