c++ - C++ 中的结构

标签 c++ c constructor struct

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

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;
}

关于c++ - C++ 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10256064/

相关文章:

Haskell:为什么不允许中缀类型构造函数?

c++ - C++ 线程中未触及的共享资源

c++ - 如何在 Windows 上制作、制作和编译 C++14

C++ 回调?我应该使用成员函数指针/委托(delegate)/事件吗?

c - 如何为具有不同条件的程序获取多个输入(整数和字符串)

c++ - 如何从预定义数组创建特定元素数组

java - Java 中构造函数调用绑定(bind)到 new 关键字?

c++ - 何时删除复制构造函数和赋值运算符?

c++ - Const Rvalue 引用以捕获不应编译的重载

C: printf 没有立即输出