# Effective c++ Item19代码练习

先看如下代码：

#include <iostream>

using namespace std;

class rational {
public:
explicit rational(int numerator = 0, int denominator = 1);
int numerator() const;
int denominator() const;
const rational operator*(const rational& rhs) const;

private:
int n,d;
};
rational::rational(int numerator, int denominator):n(numerator),d(denominator)
{

}
int rational::numerator()const
{
return n;
}
int rational::denominator()const
{
return d;
}
const rational rational::operator*(const rational& rhs) const
{
return rational(this->numerator()*rhs.numerator(),this->denominator()*rhs.denominator());
}
int main()
{
rational oneeighth(1, 8);
rational result;
result = oneeighth * 2;
result = 2 * oneeighth;

return 0;
}

error C2679: binary '*' : no operator defined which takes a right-hand operand of type 'const int' (or there is no acceptable conversion)”

#include <iostream>

using namespace std;

class rational {
public:
rational(int numerator = 0, int denominator = 1);
int numerator() const;
int denominator() const;
const rational operator*(const rational& rhs) const;

private:
int n,d;
};
rational::rational(int numerator, int denominator):n(numerator),d(denominator)
{

}
int rational::numerator()const
{
return n;
}
int rational::denominator()const
{
return d;
}
const rational rational::operator*(const rational& rhs) const
{
return rational(this->numerator()*rhs.numerator(),this->denominator()*rhs.denominator());
}
int main()
{
rational oneeighth(1, 8);
rational result;
result = oneeighth * 2;
result = 2 * oneeighth;

return 0;
}

#include <iostream>

using namespace std;

class rational {
public:
rational(int numerator = 0, int denominator = 1);
int numerator() const;
int denominator() const;
private:
int n,d;
};
rational::rational(int numerator, int denominator):n(numerator),d(denominator)
{

}
int rational::numerator()const
{
return n;
}
int rational::denominator()const
{
return d;
}

const rational operator*(const rational& lhs,const rational& rhs)
{
return rational(lhs.numerator() * rhs.numerator(),
lhs.denominator() * rhs.denominator());
}
int main()
{
rational oneeighth(1, 8);
rational result;
result = oneeighth * 2;
result = 2 * oneeighth;

return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Effective c++ Item19代码练习 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)