Stucture in C++
Stucture in C++
我遇到了这段代码,但我无法理解这段代码的功能。如果有人能解释一下,那将是一个很大的帮助.
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
是由该复制构造函数创建的,并且i
和j
从未初始化,因此当您尝试打印它们时,您会得到内存中为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)
}
总之,解决方法是这样做:
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 说明符与等号左侧显示的任何内容无关。它只说等号的右侧不会被修改。
相关文章:
- netcat command in c++
- Difference in displaying cv2 Mat
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 创建具有 new in 函数和"this is nullptr"异常的对象
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 有人安装"IITB Simplecpp in mac"吗?
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 如何修复"error: ‘_1’ was not declared in this scope"?
- Softmax Implementation in C++
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- IF-nesting in c++
- Gurobi GRBModel and GRBmodel in C++
- Tensorflow Hub in C++
- Centos7 g++ "to_string is not in a member of std"
- InitializeCriticalSectionEx Not Located In KERNEL32.Dll
- 将 lambda 表达式传递给 std::function in C++
- @CPPFLAGS@在 Makefile.in 中意味着什么?
- std::async from std::async in windows xp