【发布时间】:2015-12-24 19:51:01
【问题描述】:
好吧,我有一个名为 Fractions 的构造函数,它接受两个整数作为参数,然后我应该有一个名为 add() 的方法,它应该是一个 const int,它接受构造函数 Fractions 作为参数,然后是返回分数。
但是,我不断收到错误消息:“不存在从“Fraction”到“const int”的合适转换函数”
过去几个小时一直在搜索谷歌,但我似乎找不到任何有关如何绕过此问题的相关信息。对此的任何帮助将不胜感激,谢谢!
#include <iostream>
#include <conio.h>
#include <sstream>
#include "homework3.h"
using namespace std;
//Provide all missing parts for the class declarations
class Fraction {
public:
Fraction(){
}
Fraction(const int numerator, const int denominator) {
Fraction::numerator = numerator;
Fraction::denominator = denominator;
}
const int add(Fraction &f1) {
return f1;
}
string getString();
private:
int numerator = 0;
int denominator = 0;
};
string Fraction::getString() {
//Returns a string of the fraction.
stringstream ss;
ss << numerator << "/" << denominator;
return ss.str();
}
int main() {
//Test book problems
Fraction f1(3, 5);
Fraction f2(7, 8);
Fraction f3 = f1.add(f2);
Fraction f4 = f1.add(4);
Fraction f5 = f1 + f2;
cout << f3.getString() << endl; //These should display 59/40
cout << f4.getString() << endl; //These should display 23/5
cout << f5.getString() << endl; //These should display 59/40
f3 = f1.subtract(f2);
f4 = f1.subtract(4);
f5 = f1 - f2;
cout << f3.getString() << endl; //These should display -11/40
cout << f4.getString() << endl; //These should display -17/5
cout << f5.getString() << endl; //These should display -11/40
f3 = f1.multiply(f2);
f4 = f1.multiply(4);
f5 = f1 * f2;
cout << f3.getString() << endl; //These should display 21/40
cout << f4.getString() << endl; //These should display 12/5
cout << f5.getString() << endl; //These should display 21/40
f3 = f1.divide(f2);
f4 = f1.divide(4);
f5 = f1 / f2;
cout << f3.getString() << endl; //These should display 24/35
cout << f4.getString() << endl; //These should display 3/20
cout << f5.getString() << endl; //These should display 24/35
//Now for some fun...
f5 = (f1 * f2) / (f3 - f4) + (f5 + f2);
cout << f5.getString() << endl; //These should display 10671000/4200000
cout << "Press any key to continue" << endl;
getch();
return 0;
}
【问题讨论】:
-
似乎有些混乱。您的函数 add() 接受 Fraction 并返回 int - 但您正试图从中返回 Fraction 对象。不知道你真正想做什么。
-
返回值f1不是Fraction吗?
-
不是你给的签名。
const int是返回值。这没有意义。此外,您的 add 实现没有添加任何内容。 -
你应该有 2 个函数
Fraction& add(int val)和Fraction& add(const Fraction & val)而不是const int add(Fraction &f1) -
哦,好吧,我明白了。出于某种原因,我从来没有想过我可以将方法声明为 Fraction 类型
标签: c++ methods constructor