最近在看《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/