Effective c++ Item19代码练习

 先看如下代码:

例1:

#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)”

 

报错原因:第一行是因为rational 的构造函数是explicit,此时不允许将整数2隐式转换成rational类,所以报错,第二行报错原因:

对象oneeighth 是一个包含operator*函数的类的实例,所以编译器调用了那个函数。而整数2没有相应的类,所以没有operator*成员函数,故报错。

 

将以上代码修改为如下:

例2:

#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;
}


此时只有一行报错,那如何修改这个错误呢?

例3:

#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 Modern C++ 无水印pdf

2017年09月22日 3.87MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭