#include<cassert>#include<iostream>classFraction{private:intm_numerator{};intm_denominator{};public:// 默认构造函数Fraction(intnumerator=0,intdenominator=1):m_numerator{numerator},m_denominator{denominator}{assert(denominator!=0);}// 拷贝构造函数Fraction(constFraction&fraction):m_numerator{fraction.m_numerator},m_denominator{fraction.m_denominator}// 注意:我们可以直接访问参数 fraction 的成员变量,因为它们都是 Fraction 类的{// no need to check for a denominator of 0 here since fraction must already be a valid Fractionstd::cout<<"Copy constructor called\n";// just to prove it works}friendstd::ostream&operator<<(std::ostream&out,constFraction&f1);};std::ostream&operator<<(std::ostream&out,constFraction&f1){out<<f1.m_numerator<<'/'<<f1.m_denominator;returnout;}intmain(){FractionfiveThirds{5,3};// 直接初始化,调用 Fraction(int, int) 构造函数FractionfCopy{fiveThirds};// 直接初始化——使用拷贝构造函数 std::cout<<fCopy<<'\n';}
#include<cassert>#include<iostream>classFraction{private:intm_numerator{};intm_denominator{};// 私有拷贝构造函数Fraction(constFraction&fraction):m_numerator{fraction.m_numerator},m_denominator{fraction.m_denominator}{// no need to check for a denominator of 0 here since fraction must already be a valid Fractionstd::cout<<"Copy constructor called\n";// just to prove it works}public:// Default constructorFraction(intnumerator=0,intdenominator=1):m_numerator{numerator},m_denominator{denominator}{assert(denominator!=0);}friendstd::ostream&operator<<(std::ostream&out,constFraction&f1);};std::ostream&operator<<(std::ostream&out,constFraction&f1){out<<f1.m_numerator<<'/'<<f1.m_denominator;returnout;}intmain(){FractionfiveThirds{5,3};// 直接初始化 Fraction,调用 Fraction(int, int)FractionfCopy{fiveThirds};// 拷贝构造函数是私有的,编译器会报错。std::cout<<fCopy<<'\n';}
#include<cassert>#include<iostream>classFraction{private:intm_numerator{};intm_denominator{};public:// Default constructorFraction(intnumerator=0,intdenominator=1):m_numerator{numerator},m_denominator{denominator}{assert(denominator!=0);}// Copy constructorFraction(constFraction&fraction):m_numerator{fraction.m_numerator},m_denominator{fraction.m_denominator}{// no need to check for a denominator of 0 here since fraction must already be a valid Fractionstd::cout<<"Copy constructor called\n";// just to prove it works}friendstd::ostream&operator<<(std::ostream&out,constFraction&f1);};std::ostream&operator<<(std::ostream&out,constFraction&f1){out<<f1.m_numerator<<'/'<<f1.m_denominator;returnout;}intmain(){FractionfiveThirds{Fraction{5,3}};std::cout<<fiveThirds;return0;}