c++ - 通过示例了解复制构造函数和赋值运算符

标签 c++

最近在看《An Introduction to Design Patterns in C++ with Qt 4》这本书,我被下面的例子弄糊涂了(代码来自书中,自己做了一些小修改):

“分数.h”

class Fraction
{
public:
    Fraction(int n, int d): m_Numer(n), m_Denom(d) {
        ++ctors;
    }

    Fraction(const Fraction& other)
        : m_Numer(other.m_Numer), m_Denom(other.m_Denom) {
        ++copies;
    }

    Fraction& operator = (const Fraction& other) {
        m_Numer = other.m_Numer;
        m_Denom = other.m_Denom;
        ++assigns;
        return *this;
    }

    Fraction multiply(Fraction f2) {
        return Fraction (m_Numer*f2.m_Numer, m_Denom*f2.m_Denom);
    }

    static void report();

private:
    int m_Numer, m_Denom;
    static int assigns;
    static int copies;
    static int ctors;
};

“ main.cpp ”

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

int Fraction::assigns = 0;
int Fraction::copies = 0;
int Fraction::ctors = 0;

void Fraction::report()
{
    cout<<"[assigns: "<<assigns<<", copies: "<<copies<<", ctors: "<<ctors<<"]\n\n";
}

int main()
{
    Fraction twothirds(2, 3); // It calls a constructor
    Fraction threequarters(3, 4); // It calls a constructor
    Fraction acopy(twothirds); // It calls a copy constructor
    Fraction f4 = threequarters;  
    // [Question A]: The book says it's using a copy constructor 
    //               but I don't see how. Isn't it an assignment?

    cout<<"after declarations\n";
    Fraction::report();  //output: [assogns: 0, copies: 2, ctors: 2]

    f4 = twothirds;  // It's an assignment using the assignment operator
    cout<<"before multiply\n";
    Fraction::report();  //output: [assogns: 1, copies: 2, ctors: 2]

    f4 = twothirds.multiply(threequarters);
    cout<<"after multiply\n";
    Fraction::report();  //output: [assogns: 2, copies: 3, ctors: 3]
    // [Question B]: How does the frunction "multiply" creates three Fraction objects?

    return 0;
}

作为我在 main.cpp 中留下的评论,我有 2 个问题。

[问题 A]:为什么 Fraction f4 = threequarters 使用复制构造函数而不是赋值?

[问题 B]:函数“乘”如何创建三个 Fraction 对象?

特别是对于问题 B,我无法弄清楚这三个对象来自哪里。

请帮助我理解这些概念。提前致谢。

最佳答案

问题 A:为什么 Fraction f4 = threequarters 使用复制构造函数而不是赋值?

答案A:那是C++语言的定义。如果你用过

Fraction f4;
f4 = threequarters; 

然后第二行将使用赋值运算符。

问题 B:函数“相乘”如何创建三个 Fraction 对象?

答案B:

当您调用multiply 时,参数f2 是使用复制构造创建的。

线

return Fraction (m_Numer*f2.m_Numer, m_Denom*f2.m_Denom);

使用常规构造函数构造对象。

线

f4 = twothirds.multiply(threequarters);

multiply中构造的对象分配给f4

关于c++ - 通过示例了解复制构造函数和赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22602197/

相关文章:

java - 如何使用套接字发送位图?

c++ - 如何检测我的代码是否使用 -fno-exceptions 进行编译?

c++ - std::function 可以是类数据成员吗?

c++ - 创建一个函数,检查数组是否具有两个相反的元素,复杂度小于 n^2。 (C++)

c++ - 如何用指针交换两个变量

c++ - 在析构函数中捕获异常

c++ - opencv 文件中缺少所需的架构 x86_64

C++ 字符数组 : error while copying data

c++ - 如何强制在编译时评估 constexpr 函数

c++ - 为什么元组不会收到未使用的变量警告?