关于拷贝构造函数

论坛 期权论坛 脚本     
已经匿名di用户   2022-7-2 21:58   3729   0
#include <iostream>
#include <cstdlib>

using namespace std;
class numbered{
public:
    numbered();
    numbered(string no) :mysn_(no){};

    string mysn_;
};
numbered::numbered() {
    string s;
    s += to_string(rand());

    mysn_ = s;
}

void
f(numbered s){
    cout << s.mysn_ << endl;
}

int
main() {
    numbered a, b = a , c = b ;
    cout << "a.mysn_: " << a.mysn_ << endl;
    cout << "b.mysn_: " << b.mysn_ << endl;
    cout << "c.mysn_: " << c.mysn_ << endl;

    cout << "invoke f() for a" << endl;
    f(a);
    cout << "invoke f() for b" << endl;
    f(b);
    cout << "invoke f() for c" << endl;
    f(c);

    return 0;
}

输出

a.mysn_: 1804289383
a.mysn_: 1804289383
a.mysn_: 1804289383
invoke f() for a
1804289383
invoke f() for b
1804289383
invoke f() for c
1804289383

修改代码

#include <iostream>
#include <cstdlib>

using namespace std;
class numbered{
public:
    numbered();
    numbered(string no) :mysn_(no){};
    numbered(numbered &para);

    string mysn_;
};
numbered::numbered() {
    string s;
    s += to_string(rand());

    mysn_ = s;
}
numbered::numbered(numbered &para) {
    cout << "copy constructor invoked." << endl;
    string s;
    s += to_string(rand());
    mysn_ = s;
}

void
f(numbered s){
    cout << s.mysn_ << endl;
}

int
main() {
    numbered a, b = a , c = b ;
    cout << "a.mysn_: " << a.mysn_ << endl;
    cout << "b.mysn_: " << b.mysn_ << endl;
    cout << "c.mysn_: " << c.mysn_ << endl;

    cout << "invoke f() for a" << endl;
    f(a);
    cout << "invoke f() for b" << endl;
    f(b);
    cout << "invoke f() for c" << endl;
    f(c);

    return 0;
}

即增加

numbered(numbered &para);

numbered::numbered(numbered &para) {
    cout << "copy constructor invoked." << endl;
    string s;
    s += to_string(rand());
    mysn_ = s;
}

输出

copy constructor invoked.
copy constructor invoked.
a.mysn_: 1804289383
b.mysn_: 846930886
c.mysn_: 1681692777
invoke f() for a
copy constructor invoked.
1714636915
invoke f() for b
copy constructor invoked.
1957747793
invoke f() for c
copy constructor invoked.
424238335

继续修改代码

f(numbered s){
    cout << s.mysn_ << endl;
}

改为

f(numbered &s){
    cout << s.mysn_ << endl;
}

输出

copy constructor invoked.
copy constructor invoked.
a.mysn_: 1804289383
b.mysn_: 846930886
c.mysn_: 1681692777
invoke f() for a
1804289383
invoke f() for b
846930886
invoke f() for c
1681692777

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP