【发布时间】:2021-08-16 06:53:07
【问题描述】:
我最近学会了如何将cin 与类的对象一起使用。
istream& operator>>(istream& aliasCin, RationalNumber& r) {
double temp;
aliasCin >> temp;
r = RationalNumber(temp);
return aliasCin;
}
这是我的类 RationalNumber,正如你所看到的,我正在接受一个 double 并将它传递给我的非默认构造函数。我知道这是如何工作的,但是...
我的问题是,我还想要另一种样式来输入我的有理数,使其采用a/b 格式。
其中a 和b 是有理数的分子和分母。找到之后就可以了
RationalNumber::RationalNumber (const int& a, const int& b){
this->a = a;
this->b = b;
standardize(); // Changes the values of the object to standard form
reduce(); // Changes the Rational Number to irreducible fraction
count++;
}
首先我想到了一个字符串作为输入,在字符串中找到/的索引,然后找到a和b,但我认为应该有比这更简单的方法。还是这是我唯一的选择?
【问题讨论】:
-
你可以参考 [std::complex](en.cppreference.com/w/cpp/numeric/complex/complex ) APIS,或者只是 std::comprex 来替换你的类,特别是在生产代码中。
-
提示:使用constructor lists,避免使用
this->。