我遇到了这段代码,但我无法理解这段代码的功能。 如果有人能够解释它,那将是一个很大的帮助。
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;
}
答案 0 :(得分:1)
说明:
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;
}
答案 1 :(得分:1)
你的问题就在这一行:
A z = (a=b);
最终调用operator=
方法和Copy Constructor。执行a = b
时,它使用operator=
方法,因为a
已存在,然后返回对a
的引用。你实际上是在呼叫a.operator=(b)
。
执行A z = ...
时,它实际上使用了复制构造函数A(const A&a)
,而不是operator=
方法,因为z
尚不存在。由于复制构造函数正在创建z
,并且i
和j
永远不会被初始化,所以当您尝试将它们打印出来时,您将获得为{{保留的内存中找到的垃圾。 1}}和i
。
查看此行的另一种方法:
j
实际上是这样的:
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)
}
答案 2 :(得分:0)
三个错误:
1。A(int ii,int jj) : i(ii),j(ii /* jj here? */){}
2.复制构造函数应初始化成员:A(const A&a): i(a.i), j(a.j) {}
3.您应该在return *this
中添加operator=
:
A& operator =(const A& a){
i=a.i;j=a.j;
return *this;
}
答案 3 :(得分:-1)
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说明符与等号左侧出现的任何内容无关。它只是说等号的右边不会被修改。