理解构造函数和赋值c++

问题描述

我是 C++ 的新手,我来自 C。OOP 对我来说是一个全新的范式。

所以我会就这个愚蠢的例子提出一个问题:

#include <iostream>

class Object
{
public:
    int first;
    int second;
    Object ():first (0),second (0)
    {
        std::cout << "created1\n";
    }
    Object (int x,int y):first (x),second (y)
    {
        std::cout << "created2\n";
    }
};

int main ()
{
  Object s = { 1,1 };  //Or  Object s(1,1);
  Object d;
  s = {2,2};
  s = d;
  return 0;
}

/* Output:
    created2
    created1
    created2
*/

返回之前的两个assignment(他们是assignment?)有什么区别?

感谢您的关注。

解决方法

SingleChildScrollView( padding: EdgeInsets.all(8),child: Column( children: [ Container( margin: const EdgeInsets.all(8.0),height: 80,child: Card( semanticContainer: true,clipBehavior: Clip.antiAliasWithSaveLayer,shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12.0),),child: Column( children: [ Padding( padding: const EdgeInsets.all(12.0),child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [ Text( 'Test Campaign',style: TextStyle( color: Theme.of(context).primaryColor,fontWeight: FontWeight.bold,LineButton( onPress: () => null,label: 'View',height: 30,backgroundColor: Colors.grey[300],) ],],) 的编译器生成的 Object 而言(因为您没有实现自己的),没有区别。它需要一个 operator= 引用作为输入,但它并不关心 const Object & 来自哪里。

此代码中唯一真正的区别在于 Object 的来源。

Object 构造一个临时 s = {2,2};,将临时分配给Object,然后销毁临时。你看到的第二个 s 来自那个临时的。第一个 created2 来自 created2

Object s = { 1,1 }; 将名为 s = d; 的现有 Object 分配给 d。没有临时创建,所以这里没有输出。您看到的 s 来自 created1