运算符重载>>问题
为分数定义一个类。分数定义为两个整数之比,如1/2,64/2等等。
重载<<和>>运算符。分数以1/2,300/401这样的形式输入和输出。
要求 输入1/2 回车后 会把1赋值给类分子部分 2赋值给分母
这个问题 <<输出运算符会了 但是输入怎么做 求大神给打demo
[解决办法]
鸟语很渣,不要笑话我
简单的一个demo,输入没做错误检查
#include <iostream>
class A
{
private:
int fenzi;
int fenmu;
public:
A(int a = 0, int b = 1): fenzi(a), fenmu(b) {}
friend std::ostream& operator<< (std::ostream& out,const A& a);
friend std::istream& operator>> (std::istream& in, A& a);
};
inline std::ostream& operator << (std::ostream& out, const A& a)
{
out << a.fenzi << '/' << a.fenmu;
return out;
}
std::istream& operator>> (std::istream& in, A& a)
{
in >> a.fenzi;
while (in.get() != '/') continue;
in >> a.fenmu;
return in;
}
int main()
{
using std::cin;
using std::cout;
using std::endl;
A a;
cout << "输入一个分数:";
cin >> a;
cout << a << endl;
return 0;
}