Um zu verstehen, die Arbeits von Objekten in C++, besser zu verstehen, schrieb ich dieses Stück Code:kann nicht Überlastung des Zuweisungsoperators
using namespace std;
char n[] = "\n";
class T
{
private:
int num;
public:
T()
{
num = 0;
cout << n << (long)this % 0xFF << " created without param";
}
T (const int param)
{
num = param;
cout << n << (long)this % 0xFF << " created with param = " << param;
}
T (const T& obj)
{
num = obj.num;
cout << n << (long)this % 0xFF << " created as copy of " << (long)&obj % 0xFF;
}
const T& operator= (const T& obj)
{
if (this == &obj)
return *this;
num = obj.num;
cout << n << (long)this % 0xFF << " got assigned the data of " << (long)&obj % 0xFF;
return *this;
}
~T()
{
cout << n << (long)this % 0xFF << " destroyed";
}
int get() const {return num;}
void set (const int param) {num = param;}
};
T PlusTen (T obj)
{
T newObj(5);
newObj.set(obj.get() +10);
return newObj;
}
int main()
{
T a, b(4);
a = b;
a = PlusTen(b);
cout << n;
return 0;
}
Seiner Arbeit in Ordnung, aber wenn ich das const
-Qualifikationsspiel in „Return-Typ entfernen "und‚Parameter‘überladener Zuweisungsoperator wie diese unten:
T& operator= (T& obj) // const removed
{
if (this == &obj)
return *this;
num = obj.num;
cout << n << (long)this % 0xFF << " got assigned the data of " << (long)&obj % 0xFF;
return *this;
}
Dann diese Linie der Hauptfunktion gibt Fehler:
a = PlusTen(b);
Die Fehlermeldung Wesen:
no match for 'operator=' (operand types are 'T' and 'T')
note:
candidate is: T& T::operator=(T&)
no known conversion for argument 1 from 'T' to 'T&'
Wenn Operand Typen von ‚T‘ und ‚T‘ sind problematisch, wie die Linie kommen knapp darüber (a = b;
) völlig in Ordnung ist? Sie sind auch von Operandentypen "T" und "T" !!
fand ich einen relevanten questoin hier aber kein nützliches Detail dort:
why must you provide the keyword const in operator overloads
eine sagt es, dass, wenn wir = nicht const
in Operator verwenden wir nur für non-const
Objekte verwenden können. Aber auch bei mir sind beide Seiten nicht konstant. Warum dann Fehler? Vor allem, wenn die darüber liegende Zeile, die in den Operandentypen identisch ist, gut kompiliert wird?
Compiler verwendet: MinGW