我知道当你声明其中一个时,你可以使两个物体彼此相等。我在我的程序中测试了这个。但当我去使用任务声明时,它吓坏了。你可以使用赋值语句使两个对象彼此相等,或者只能在声明一个对象时才这样做吗?

有帮助吗?

解决方案

您已将operator =提供给某个类,以便复制另一个对象的内容。例如:

class A
{
  public:

   //Default constructor
   A();

   //Copy constructor
   A(const A&);

   //Assignment operator
    A& operator=(const A& a);
};

int main()
{
  A a; //Invokes default constructor
  A b(a); //Invokes copy constructor;
  A c;
  c = a; //Invokes assignment operator
}

其他提示

重载该对象的赋值运算符可以帮助您。 (我希望你在谈论同类的对象:))

对于赋值运算符,只需根据类实现重载赋值运算符。

当对象依赖于其他对象时,可能需要对象初始化或创建或等同于另一个对象。

在这种情况下,复制构造函数提供了最佳解决方案。因为它不会逐位将对象复制到其他对象。如果将内存动态分配给对象,则按位复制会产生问题。因此,解决方案是定义类中的copy_constructor。复制构造器引用与其参数相同类型的现有对象,并用于从现有对象创建新对象。下面是使用复制构造函数将对象与其他对象等同的示例。

#include "stdafx.h"
#include "iostream"
using namespace std;
class array
{
int *ptr;
int size;
public:
array (int sz) {
ptr = new int [sz];
size =sz;
for(int index=0;index<size;index++)
ptr[index]=size;
}
~array(){
delete[] ptr;
}
array(array &a) {
int index;
ptr=new int[a.size];
for(index=0;index<a.size;index++)
ptr[index]=a.ptr[index];
cout<<"copy_constructor invoked"<<endl;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
array num(10);
array x(num); //invokes copy_constructor
array y=num; //invokes copy consturctor

return 0;
}

此答案适用于C#。

除了Overloading = operator,您还应该覆盖等于方法。您还应该查看重载等于的指南 ()和运算符==

public struct Complex 
{
   double re, im;
   public override bool Equals(Object obj) 
   {
      return obj is Complex && this == (Complex)obj;
   }
   public override int GetHashCode() 
   {
      return re.GetHashCode() ^ im.GetHashCode();
   }
   public static bool operator ==(Complex x, Complex y) 
   {
      return x.re == y.re && x.im == y.im;
   }
   public static bool operator !=(Complex x, Complex y) 
   {
      return !(x == y);
   }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top