使用内流在类中重载>>

overloading >> in class with instream

本文关键字:gt 重载      更新时间:2023-10-16

我有以下代码:

class someclass
{
     private :
     unsinged char a; 
     public :
      ...
}

我想使用

std::istream& operator>>(std::istream &in,  someclass &x)
{
    in>>x.a;
    return in;
}
int main()
{
  someclass test;
 std::cin>>test;
 return 0;
}

我的问题是,作为用户,我想在0-255之间插入一个整数。但是,它只接受单一字符。我应该如何将其"铸造"到整数?

谢谢。

问候。

我应该如何将其"铸造"到整数?

然后使用临时整数进行输入:

std::istream& operator>>(std::istream &in,  someclass &x)
{
    int temp;
    if(!(in>>temp) || temp < 0 || temp > 255) 
        { throw std::runtime_error("Invalid input"); }
    x.a = (unsigned char)temp;
    return in;
}