2012-04-21 48 views
0

我遇到了这个代码,但我不明白这个代码的功能。 这将是一个很大的帮助,如果有人可以解释它。Stucture在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; 
} 
+3

哪一部分你不明白吗? – Cyclonecode 2012-04-21 04:03:28

+0

运算符过载部分。 如果我们将const作为常量,我们如何编辑它。 – 2012-04-21 04:04:34

+0

重载默认构造函数:http://www.java2s.com/Tutorial/Cpp/0180__Class/Overloadtheconstructor.htm – Cyclonecode 2012-04-21 04:06:42

回答

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

为什么“z”收到垃圾值? – 2012-04-21 04:12:29

+0

我不知道你的代码是用于什么,所以不能评论它是否是垃圾。但是'z =(a = b)'简单地分配'a = b',并且分配'z = a'(或b因为它们现在相同) – texasbruce 2012-04-21 04:18:14

+0

因为赋值没有在构造函数中定义 – Cyclonecode 2012-04-21 04:18:27

1

你的问题是这样的一行:

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

的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说明符强制执行。这个常量符无关与上等号的左边会出现什么。它只是说等号的右侧不会被修改。

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.You应operator=添加return *this

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