我用C++编写了这个小代码片段,输出也附加了.我无法理解为什么构造函数只被调用一次,而我可以看到两个调用是为析构函数.
据我所知,应该在第28行调用默认构造函数和重载赋值运算符.
有人可以对此有所了解:
1 #include <iostream>
2 using namespace std;
3
4 class ABC {
5 char c;
6 public:
7 ABC() {
8 cout << "default" << endl;
9 }
10 ABC(char c) {
11 this->c = c;
12 cout << c << endl;
13 }
14 ~ABC() {
15 cout << hex << this << " destructor " << c << endl;
16 }
17 void method() {
18 cout << "method" << endl;
19 }
20 void operator= (const ABC& a) {
21 cout << "operator" << endl;
22 }
23
24 };
25
26 int main() {
27 ABC b('b');
28 ABC a = b;
29 }
Run Code Online (Sandbox Code Playgroud)
Output in g++ version 4.0.1:
~/src$ g++ test.cpp
~/src$ ./a.out
b
0xbffff0ee destructor b
0xbffff0ef destructor b
Run Code Online (Sandbox Code Playgroud)
Ara*_*raK 15
ABC a = b;
Run Code Online (Sandbox Code Playgroud)
这是一个 复制构造函数而不是赋值运算符!你可以像这样重新定义它是由编译器生成的:
ABC(const ABC& other)
{
c = other.c;
cout << c << " copy constructor" << endl;
}
Run Code Online (Sandbox Code Playgroud)
如果你真的坚持不使用复制构造函数,你可以像对你的类一样添加转换操作符并忘记复制构造函数!
operator char()
{
return c;
}
Run Code Online (Sandbox Code Playgroud)
Arp*_*ius 11
您刚刚调用复制构造函数的代码,这是定义:
ABC(const ABC& a):c(a.c){
cout << "copying " << hex << &a << endl;
}
Run Code Online (Sandbox Code Playgroud)
你应该看到这样的输出:
b
copying 0x7fffebc0e02f
0x7fffebc0e02e destructor b
0x7fffebc0e02f destructor b
Run Code Online (Sandbox Code Playgroud)
如果要调用默认构造函数,然后调用赋值运算符,则必须使用两个单独的语句:
ABC b('b');
ABC a;
a = b;
Run Code Online (Sandbox Code Playgroud)