Effective C++ 条款46 需要类型转换时请为模板定义非成员函数 实现代码


Rational.h

template<typename T> class Rational;
template<typename T>
const Rational<T> doMultiply(const Rational<T>& lhs, const Rational<T>& rhs)
{
    return Rational<T>(lhs.getnumerator() * rhs.getnumerator(), lhs.getdenominator() * rhs.getdenominator());
}

template<typename T>
class Rational
{
    public:
    Rational(const T& numerator = 0, const T& denominator = 1):numerator(numerator), denominator(denominator)
    {
        //this->numerator = numerator;	// const reference以及父类没有默认构造函数的都需要在初始化类表中列出
        //this->denominator = denominator;
    }
    const T getnumerator() const	// 书上是numerator() 这是要报错的,编译器认不出这是变量还是函数
    {
        return numerator;
    }
    const T getdenominator() const
    {
        return denominator;
    }

    friend
    const Rational<T> operator*(const Rational<T>& lhs, const Rational<T>& rhs)
    {
        return doMultiply(lhs, rhs);
    }

    private:
    const T numerator;
    const T denominator;
};

main.cpp

#include<iostream>
#include "Rational.h"
using namespace std;

int main()
{
    Rational<int> onehalf(1, 2);
    Rational<int> result = onehalf * 2;
    cout << result.getdenominator() << " " << result.getnumerator() << endl;

    Rational<int>result1 = 2 * onehalf;
    cout << result1.getdenominator() << " " << result1.getnumerator() << endl;
    return 0;
}


你可能感兴趣的:(C++,Class,reference,编译器)