C++ 中复制构造函数的不确定行为

问题描述 投票:0回答:1

作为一名学生,我正在测试调用复制构造函数的各种方法。我遇到了其中 3 个:

Test t2 = t1 // 1 ; 
Test t3(t1) // 2 ; 
Test t4 ;  // 3 ;
t4 = t1 ;

显式定义的复制构造函数将 10 添加到 t1 的每个数据成员。前两个工作正常并调用显式的。然而,第三种方法调用隐式复制构造函数,即没有发生 10 的加法。

我的代码:

#include <iostream>
using namespace std ; 
class Test
{
    int m,n ; 
    public: 
    Test() ; 
    Test(int,int) ; 
    ~Test() ; 
    Test(Test&) ; 
    void showData() ; 
}; 
inline Test::Test(Test& t)
{
    cout<<"called"<<endl ;
    m = t.m + 10 ; 
    n = t.n + 10 ; 
}
inline Test::Test(){}
inline Test::Test(int m,int n)
{
    Test::m = m ; 
    Test::n = n ; 
}
inline Test::~Test(){}
inline void Test::showData()
{
    cout<<m<<" "<<n<<endl ; 
}
int main()
{
    Test t1(3,4) ; 
    t1.showData() ; 
    Test t2(t1) ; 
    t2.showData() ;
    Test t3 = t1 ;
    t3.showData() ;
    Test t4 ; //calls the implicit one 
    t4 = t1 ; 
    t4.showData() ;
    return 0 ; 
}

输出:

3 4
called
13 14
called
13 14
3 4

我尝试重载赋值(=)运算符来手动解决第三种方法的问题,该方法确实有效,但我想知道为什么第三种方法调用隐式复制构造函数,即使已显式提供定义。

c++ constructor copy-constructor explicit
1个回答
0
投票

这是一个 复制构造函数

Test t2 = t1;  // calls Test::Test(const Test& t)

而下面是一个 复制赋值运算符

Test t4 ;  // calls Test() constructor
t4 = t1 ;  // calls Test& operator=(const Test& t)
© www.soinside.com 2019 - 2024. All rights reserved.