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

c – 为什么在声明对象时,构造函数和赋值运算符都没有执行?

发布时间:2020-12-16 10:18:05 所属栏目:百科 来源:网络整理
导读:测试程序是 #include iostreamusing namespace std;class A {public: A (): I(0) {cout "default construcot" endl; }; explicit A (int i): I(i) {cout "another construcot" endl; }; A (const A a): I(a.I) {cout "copy constructor" endl; } A operator
测试程序是

#include <iostream>
using namespace std;

class A
   {public:
       A (): I(0) {cout << "default construcot" << endl; };
       explicit A (int i): I(i) {cout << "another construcot" << endl; };
       A (const A& a): I(a.I) {cout << "copy constructor" << endl; }
       A& operator = (const A& a)
          {cout << "assignment operator" << endl; 
           if (this == &a) return *this; 
           I = a.I;
           return *this; 
          }
       void show () {cout << I << endl; };
    private:
       int I;
   };

int main ()
   {A a = A(1);
    A b;
    b = A(2);
    a.show();
    b.show();
    return 0;
   }

输出

another construcot
default construcot
another construcot
assignment operator
1
2

表明,与’b’不同的对象’a’是从A(1)“直接”构造而不执行赋值运算符.但复制构造函数也没有被执行.为什么?在这种情况下,有没有办法强制执行赋值运算符?如果我写的话,我会期待这种行为

A a (1);

但我想要

A a = A(1);

这与第一种情况不同.或不?

(事实上??,当我有一个从A派生的B类并且希望A的赋值运算符处理A a = B(…)之类的声明时,会出现问题.)

解决方法

Why

该标准允许编译器优化复制结构.这不是一个赋值,因为它是声明的一部分(所以如果没有完成优化,它将导致一个临时对象,然后将临时复制构造成a).

Is there a way to force execution of assignment operator in this case.

这取决于你的编译器.但是我不知道有什么可以让你强迫这个(但我从来没有试过把它关掉).尝试关闭编译器正在执行的所有优化.

I would expected such behavior if I wrote: A a (1);

该标准明确指出您的版本可以优化到此.

I have a class B derived from A and want A’s assignment operator to handle declaration like A a = B(…).)

如果你这样做,你将切片B并只分配B对象的A部分.
你想使用参考吗?

A const& a = B();

(编辑:李大同)

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

    推荐文章
      热点阅读