#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 ¶);
string mysn_;
};
numbered::numbered() {
string s;
s += to_string(rand());
mysn_ = s;
}
numbered::numbered(numbered ¶) {
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 ¶);
numbered::numbered(numbered ¶) {
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 |