C++ 操作员的问题=
我构建了两个类,C++ 操作员的问题=,c++,C++,我构建了两个类,Multime(意思集)和Array。我需要重载*操作符来进行集合交集并将结果分配给另一个集合。我决定也重载=操作符,以解决后者。这是Multime的标题: class Multime{ private: Array a; int* n; public: Multime(); Multime(Multime& ob); ~Multime(); void Transformare(Array t);//transforms a
Multime
(意思集)和Array
。我需要重载*
操作符来进行集合交集并将结果分配给另一个集合。我决定也重载=
操作符,以解决后者。这是Multime的标题:
class Multime{
private:
Array a;
int* n;
public:
Multime();
Multime(Multime& ob);
~Multime();
void Transformare(Array t);//transforms an array into a set by eliminating duplicates
int& operator[] (int x);//makes ob[i] return ob.a[i];
Multime& operator+ (Multime& y);
Multime& operator=(Multime& y);
Multime& operator* (Multime& y);
void Afisare();//outputs the array in the object that called it
};
这是数组的标头:
class Array{
private:
int* c;///the array
int len, capacity;
public:
Array();
void Append(int);
~Array();
int& operator[] (int);//makes ob[i] retuen ob.c[i]
void Afisare();
void Sortare();//sorts the array
friend class Multime;
};
这就是我重载=运算符的方式:
Multime& Multime::operator=(Multime& ob)
{
if(*n!=0) {
std::cout<<"don't overwrite a nonvoid set";
std::cout<<"the result should have been "<<ob.Afisare();
std::cout<<"n="<<*n;
}
else
{
if(this!=&ob)
{
for(int i=0; i<*ob.n; i++)
{
a.Append(ob.a[i]);
}
*n=*(ob.n);
}
}
return *this;
}
Multime& Multime::operator* (Multime& y)
{
Multime q;
for(int i=0; i<*n; i++)
{
for(int j=0; j<*y.n; j++)
{
if(a[i]==y.a[j])
q.a.Append(a[i]);
}
}
*q.n=q.a.len;
*this=q;
return *this;
}
输出
don't overwrite a nonvoid set
the result should have been 2
n=3
我很困惑为什么
n
是3
,尽管它是刚刚创建的。由于操作符*
末尾的这一行,您得到了输出:
*this=q;
您正在覆盖this
参数(调用者提供的mul1
),该参数不是空的Multime
对象
基本上,您的两个运算符*
的行为不象乘法运算符,因为它修改了其中一个参数。它的行为是一个操作符*=
函数。成员运算符*
的签名通常类似于
Multime Multime::operator*(const Multime& y) const
其中它不会修改任何一个参数,并返回一个新对象。您可以从末尾删除有问题的赋值,只需使用
return q代码>请显示重现问题所需的所有代码。请给我看看;多重ME(多重ME&ob)`构造函数为什么multimen::n
是指针?它指向什么?看看如何创建一个。您还没有显示所有相关的代码(如构造函数)。这个答案解决了眼前的问题,但还有其他问题潜伏着。
Multime Multime::operator*(const Multime& y) const