【发布时间】:2014-10-30 13:00:09
【问题描述】:
[Error] no matching function for call to 'fraction::add(fraction&, fraction&)'
line 105 which is
f3.add( f1, f2);
这是我在尝试编译时收到的错误消息。
实例: 我正在尝试创建一个“分数”类,它允许我的讲师预设的 int main() 从中执行。到目前为止,我已经构建了一个简单的类,并且正在尝试编译以查看它是否有效。
'My class:
class fraction
{
private:
long num, den;
public:
void setNum(long i_num)
{
num=i_num;
}
void setDen(long)
{
}
long getNum()
{
return num;
}
long getDen()
{
return den;
}
fraction()
{
num = 1;
den = 1;
}
fraction(int n, int d)
{
num = n;
if (d==0)
{
cout << "Cannot divide by zero" << endl;
exit(0); // will terminate the program if division by 0 is attempted
}
else
den = d;
}
fraction add(fraction otherFraction)
{
int n = num*otherFraction.den+otherFraction.num*den;
int d = den*otherFraction.den;
return fraction(n/gcd(n,d),d/gcd(n,d));
}
fraction sub(fraction otherFraction)
{
int n = num*otherFraction.den-otherFraction.num*den;
int d = den*otherFraction.den;
return fraction(n/gcd(n,d),d/gcd(n,d));
}
fraction mult(fraction otherFraction)
{
int n = num*otherFraction.num;
int d = den*otherFraction.den;
return fraction(n/gcd(n,d),d/gcd(n,d));
}
fraction div(fraction otherFraction)
{
int n = num*otherFraction.den;
int d = den*otherFraction.num;
return fraction(n/gcd(n,d),d/gcd(n,d));
}
int gcd(int n, int d)
{
int remainder;
while (d != 0)
{
remainder = n % d;
n = d;
d = remainder;
}
return n;
}
void print() // Display method
{
if (den == 1) // e.g. fraction 2/1 will display simply as 2
cout << num << endl;
else
cout << num << "/" << den << endl;
}
};'
我导师的 int main():
int main ( )
{ // define seven instances of the class fraction
fraction f1, f2, f3, f4, f5, f6, f7;
//set values for the numerator and denominator to f1 and print
//them
f1.setDen( 2L);
f1.setNum( 0L);
f1.print();
//set values for the numerator and denominator to f2 and print them
f2.setDen( 4L);
f2.setNum( 3L);
f2.print();
f3.add( f1, f2);
f3.print();
f4.sub( f1, f2);
f4.print();
f5.mult( f1, f2);
f5.print();
f6.div( f1, f2);
f6.print();
f7.inc(f1);
f7.print(f1);
我的导师告诉我们不要以任何方式编辑 main()。
我已经追溯到类中的方法
fraction add(fraction otherFraction)
{
int n = num*otherFraction.den+otherFraction.num*den;
int d = den*otherFraction.den;
return fraction(n/gcd(n,d),d/gcd(n,d));
}
如何在 main() 中传递变量,以便它们在课堂上工作? 我只被教过一种做事方式,这是我的第一堂面向对象的课程。他在教不同的组织方式,我不理解。 大约一周后(在线课程),他还没有通过电子邮件回复我。
任何提示/提示将不胜感激。 谢谢。
【问题讨论】:
-
在类声明文件中添加函数声明
fraction add(const fraction&, const fraction&),并为其添加实现。