当对象包含在c ++中的另一个对象中时,为什么复制构造函数被调用两次?

时间:2017-01-05 16:15:08

标签: c++

    Dim wsrng As Range
    For Each wsrng In Range("K4:K10")
        If wsrng.Value = 0 Then
            Selection.FormatConditions.Delete
        End If
    Next wsrng

V4类包含另一个类V3,V4的对象由V3的存在对象初始化,因此V4的构造函数将调用V3的复制构造函数,我认为复制构造函数将被调用一次,但结果显示它被称为tiwce,为什么会这样?

编译代码:

//V4.cpp
#include <iostream>
using namespace std;
class V3 {
private:
    double x, y, z;
public:
    V3(double a, double b, double c): x(a), y(b), z(c) {
        cout << "V3(double, double, double)" << endl; 
    }
    V3(const V3 &a): x(a.x), y(a.y), z(a.z) {
        cout << "V3(const V3 &)" << endl;
    }
};
class V4 {
private:
    V3 xyz;
    double time;
public:
    V4(V3 a, double t): xyz(a), time(t) {
        cout << "V4(V3, double)" << endl;
    }
};
int main(void)
{
    V3 xyz(1.0, 2.0, 3.0);
    double t(4.0);
    V4 xyzt(xyz, t);

    return 0;
}

并运行:

g++ V4.cpp -o V4 -Wall

结果:

./V4

所以查看结果,为什么V3复制构造函数被调用两次? 我的操作系统是Lubuntu16.04,g ++是5.4.0

1 个答案:

答案 0 :(得分:4)

您在V3 a的构造函数中按值V4,导致额外的不必要的副本。你应该const&

class V4 {
private:
    V3 xyz;
    double time;
public:
    V4(const V3& a, double t): xyz(a), time(t) {
//     ^^^^^^^^^^^
        cout << "V4(V3, double)" << endl;
    }
};

wandbox example