加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C构造函数调用

发布时间:2020-12-16 06:47:26 所属栏目:百科 来源:网络整理
导读:我在C中写了这个小代码片段,输出也附加了. 我无法理解为什么构造函数只被调用一次,而我可以看到两个调用是为析构函数. 据我所知,应该在第28行调用默认构造函数和重载赋值运算符. 有人可以对此有所了解: 1 #include iostream 2 using namespace std; 3 4 cla
我在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 }
Output in g++ version 4.0.1:
~/src$g++ test.cpp
~/src$./a.out 
b
0xbffff0ee destructor b
0xbffff0ef destructor b

解决方法

您刚刚调用复制构造函数的代码,这是定义:

ABC(const ABC& a):c(a.c){
    cout << "copying " << hex << &a << endl;
}

你应该看到这样的输出:

b
copying 0x7fffebc0e02f
0x7fffebc0e02e destructor b
0x7fffebc0e02f destructor b

如果要调用默认构造函数,然后调用赋值运算符,则必须使用两个单独的语句:

ABC b('b');
  ABC a;
  a = b;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读