Stucture in C++

Stucture in C++

本文关键字:C++ in Stucture      更新时间:2023-10-16

我遇到了这段代码,但我无法理解这段代码的功能。如果有人能解释一下,那将是一个很大的帮助.

struct A{
   int i,j;
   A(int ii,int jj) : i(ii),j(ii){}
   A(const A&a){
           }
   A& operator =(const A& a){
               i=a.i;j=a.j;
   }
};
int main()
{
int i;
A a(1,2);
A b(2,3);
A z = (a=b);
cout<<z.i<<" "<<z.j<<endl;
system("pause");
return 0;
}

解释:

struct A{
   int i,j;//members i and j
   A(int ii,int jj) : i(ii),j(ii){} //A constructor. Short form of A(int ii,int jj){i = ii;j = jj;} Original code is wrong too. Should be j(jj) instead of j(ii)
   A(const A&a){}//Another constructor. It is missing the assignment
   A& operator =(const A& a){
               i=a.i;j=a.j;
   }//Equal operator overload definition for A = another A. It copies the data from another A and assign to this new one
};

完整的工作代码:

#include <iostream>
using namespace std;
struct A{
   int i,j;
   A(int ii,int jj) : i(ii),j(jj){}
   A(const A&a){i=a.i;j=a.j;}
   A& operator =(const A& a){i=a.i;j=a.j;}
};
int main()
{
    int i;
    A a(1,2);
    A b(2,3);
    A z = (a=b);
    cout<<z.i<<" "<<z.j<<endl;
    return 0;
}

你的问题是这一行:

A z = (a=b);

它最终会同时调用您的operator=方法和复制构造函数。 执行 a = b 时,它使用 operator= 方法,因为a已经存在,然后返回对 a 的引用。 你本质上是在打电话给a.operator=(b).

A z = ...被执行时,它实际上使用复制构造函数A(const A&a),而不是operator=方法,因为z尚不存在。 由于z是由该复制构造函数创建的,并且ij从未初始化,因此当您尝试打印它们时,您会得到内存中为ij保留的任何垃圾。

查看此行的另一种方式:

A z = (a=b);

其实是这样的:

A z(a.operator=(b));

下面是一个完整的示例:

int main()
{
    A a(1,2);
    A b(2,3);
    a = b; //calls A& operator=(const A& a)
    A z = a; //calls A(const A& a)
}

总之,解决方法是这样做:

A(const A& a)
   {
        i = a.i;
        j = a.j;
   }

三个错误:

1. A(int ii,int jj) : i(ii),j(ii /* jj here? */){}

2.复制构造函数应初始化成员:A(const A&a): i(a.i), j(a.j) {}

3.您应该在operator=中添加return *this

A& operator =(const A& a){
    i=a.i;j=a.j;
    return *this;
}

OP问the operator overloadin part. if we take a as const how can we edit it.

运算符重载部分为:

A& operator =(const A& a){
           i=a.i;j=a.j;

}

当你写a=b时,你只期望a改变而不是b。这是由函数参数定义中的 const 说明符强制执行的。此 const 说明符与等号左侧显示的任何内容无关。它只说等号的右侧不会被修改。