c++中的操作符重载,无法调用双参数构造函数
operator overloading in c++ , could not call the two parameter constructor
我的程序要求我在c++中使用操作符重载的概念将两个有理数相加。程序应该读取整行(例如:2/3 + 3/4)并返回结果。程序中的构造函数应该验证有理数(当在分母中输入0时应该显示错误(例如:2/0 + 3/4)。
我写了下面的程序,但是我不能调用我的两个参数构造函数,所以零参数构造函数被执行,并且每次输出2的结果。有谁能帮我一下吗?
#include<iostream>
#include <string>
using namespace std;
class rational {
int numer;
int denom;
int result;
public:
rational():numer(1),denom(1) {}
rational(int a, int b) {
if(b==0) {
cout<<"Eror Denominator should be greater than zero";
exit(0);
} else {
numer=a;
denom=b;
}
}
int gcd(int a, int b);
friend istream& operator>>( istream &input, rational &r ) {
int x,y;
input>>x;
input.ignore(1);
input>>y;
rational(x,y); // here I am not able to call my constructor
return input;
}
rational operator+(rational c2) {
rational temp;
rational g;
temp.numer=(c2.numer*denom)+(numer*c2.denom);
temp.denom=c2.denom*denom;
result=g.gcd(temp.numer,temp.denom);
temp.numer=temp.numer/result;
temp.denom=temp.denom/result;
return temp;
}
friend ostream &operator<<( ostream &output, const rational &r ) {
if(r.denom==1) {
output <<r.numer;
return output;
} else {
output <<r.numer<<"/"<<r.denom;
return output;
}
}
};
int rational:: gcd(int a, int b) {
int gc=1;
for(int i=1;i<=a&&i<=b;i++) {
if((a%i==0)&&(b%i==0)) {
gc=i;
}
}
return gc;
}
int main() {
cout.setf(ios::boolalpha);
string op;
rational r1;
rational r2;
cin>>r1>>op>>r2;
cout<<(r1+r2)<<endl;
int i;
cin>>i;
}
下面将简单地构建新的rational
对象并销毁,它不会分配当前对象
rational(x,y);
您需要在重载<<
操作符
input >> r.numer >> r.denom;
要实际执行验证或输入的数据,可以创建单独的函数,该函数将在执行任何计算之前被调用
#include <stdexcept>
bool rational::validate( ) const // private member function
{
return denom == 0 ? false : true ;
}
friend istream& operator>>( istream &input, rational &r )
{
input >> r.numer >>r.denom;
if( !r.validate () )
throw std::runtime_error("Bad Input") ;
return input;
}
你也可以在参数化构造函数中调用这个validate。请记住,第二个构造函数将在调用带参数的对象并使用该对象时调用。
参见 here
对于这个语句,
rational r1;
调用有理数对象r1的默认构造函数
rational():numer(1),denom(1)
{
}
而你正在打印:
cout<<(r1+r2)<<endl;
所以,你的结果是2,因为默认值设置为1。
这不是你期望的工作方式:
cin >> r1>> op>> r2;
你需要为你的对象(类)重载流操作符>>,然后在那里添加你的逻辑。
friend istream& operator>>( istream &input, rational &r )
{
//push the values into object
input >> r.numer >>r.denom;
}
相关文章:
- 为什么即使我调用参数化构造函数也会调用默认构造函数?
- 什么是仅调用一次并调用参数的控制台应用
- 调用参数排列不变函数 f(i++, i++)
- 调用参数不是原子参数的函数是此代码引发异常的原因吗?
- 如何使可调用参数的签名在C++模板中可见?
- x64 函数调用参数推送/移动顺序 (MSVC)
- 如何调用参数由另一个函数生成的函数?
- 从从可调用参数创建的线程对象参数移动构造 C++11 线程
- 正确调用参数化 std::函数
- 是否允许在调用参数中使用类型名 T
- 我不知道如何调用参数为节点类型的函数
- 函数调用参数列表 (C++) 中的空格
- Valgrind 错误:系统调用参数 epoll_pwait(sigmask) 指向不可寻址的字节
- 这C++代码如何让我调用参数数量错误的函数
- 在计算后,在基类之后调用参数化构造函数
- NPAPI调用参数包装
- 在类组合中调用参数化构造函数
- 为什么在创建类对象数组时不能调用参数化构造函数?
- 如何在 for 循环中调用参数化构造函数
- 如何在PIMPL设计模式中调用参数化构造函数