【问题标题】:Stucture in C++C++ 中的结构
【发布时间】:2012-04-21 03:59:45
【问题描述】:

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

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

【问题讨论】:

  • 哪部分不明白?
  • 运算符重载部分。如果我们将 a as const 我们如何编辑它。
  • 也许可以编辑帖子以反映这一点?您只需要展示大约两行代码并提出一个非常具体的问题。

标签: c++ c constructor struct


【解决方案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;
}

【讨论】:

  • 为什么“z”会收到垃圾值?
  • 我不知道你的代码是用来做什么的,所以不能评论它是否是垃圾。但是z=(a=b) 只需分配a = b,然后分配z = a(或b,因为它们现在相同)
  • 因为赋值没有在构造函数中定义
  • z 收到一个垃圾值,因为它调用了您留空的复制构造函数,而不是您定义的 operator= 方法。
  • 哦,你的意思是……是的。 A z=a 调用 A(const A& a) 而不是 = 运算符;原因未知,但这是规则。但是如果你做A z(0,0); z = a;,那么它会调用=。
【解决方案2】:

你的问题是这一行:

A z = (a=b);

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

A z = ...被执行时,它实际上使用了Copy Constructor A(const A&amp;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;
   }

【讨论】:

    【解决方案3】:

    三个错误:

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

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

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

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

    【讨论】:

      【解决方案4】:

      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 说明符与等号左侧出现的任何内容无关。它只是说等号的右边不会被修改。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-18
        • 2014-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多