c++类型转化
More Effective C++的笔记
4.1 Item M5:谨慎定义类型转换函数
1 #include <iostream> 2 3 4 class Rational { 5 public: 6 explicit Rational(int numerator = 0, int denominator = 1); 7 //拷贝构造函数不需要explicit修饰,否则需要再定义一个 8 //非const构造参数的构造函数,此处允许的非const转const是无害转换 9 Rational(const Rational &); 10 ~Rational(); 11 public: 12 //Rational a, b, c; 13 //a = b = c; 这个表达式依赖于这个operator = 重载函数返回一个自身的引用 14 Rational& operator = (const Rational &);
15 //使用asDouble函数替代double()可以防止编译器的隐式的类型转换 16 //Rational r; std::cout << r; 17 //如果没有定义operator <<, 将会打印一个double值而不是一个期待的分数值 18 //因为r被编译器隐式的转换成了double值 19 operator double () const; 20 double asDouble() const { return static_cast<double>(m_numerator) / m_denominator; } 21 int numerator(void) const { return m_numerator; } 22 int denominator(void) const { return m_denominator; } 23 private: 24 int m_numerator; 25 int m_denominator; 26 }; 27 28 Rational operator *(const Rational &lhs, const Rational &rhs) 29 { 30 int numerator = lhs.numerator() * rhs.numerator(); 31 int denominator = lhs.denominator() * rhs.denominator(); 32 33 Rational result(numerator, denominator); 34 35 return result; 36 } 37 38 Rational::Rational(int numerator, int denominator) 39 :m_numerator(numerator), m_denominator(denominator) 40 { 41 42 } 43 44 Rational::Rational(const Rational &rhs) 45 :m_numerator(rhs.numerator()), m_denominator(rhs.denominator()) 46 { 47 48 } 49 50 Rational::~Rational() 51 { 52 53 } 54 55 Rational::operator double() const 56 { 57 return static_cast<double>(m_numerator) / m_denominator; 58 } 59 60 Rational& Rational::operator = (const Rational &rhs) 61 { 62 m_numerator = rhs.numerator(); 63 m_denominator = rhs.denominator(); 64 65 return *this; 66 } 67 68 class Base{ 69 public: 70 Base() { } 71 virtual ~Base() { } 72 private: 73 int GetNum(void) const { return m_num; } 74 75 int m_num; 76 }; 77 78 class Derived : public Base { 79 public: 80 Derived() { } 81 virtual ~Derived() { } 82 83 //GetNum函数是Base类的私有成员,无法被Derived继承 84 // void printNum(void) { std::cout << GetNum() << std::endl; } 85 }; 86 87 int main(void) 88 { 89 Rational a; 90 double d = 0.5 * a; 91 int i = 2 * a; 92 93 Rational b, c; 94 c = b * a; 95 96 return 0; 97 }