我正在读一本C++的书。该程序试图创建一个对象的向量。这是我不明白的部分
class X {
public:
X();
X(int m) {
temp = x;
}
int temp;
X &operator =(int z) {
temp = z;
return *this;
}
private :
// Some functions here
}上面这行是什么意思?这是某种重载吗?那该怎么做呢?
发布于 2012-02-07 03:44:03
我假设你有一个打字错误,并且这行实际上是这样的:
X &operator =(int z) {&意味着返回类型是一个引用;您应该将其读作返回X &类型的函数operator =。
发布于 2012-02-07 03:46:30
如果你稍微改变一下间距,意思可能会更清楚:
X& operator= (int z)这是赋值操作符operator=的重载,它接受一个int参数,并返回一个对class X的引用。
您可以使用它为对象分配一个整数值:
X x;
x = 42; // calls the overloaded operator返回值允许您链接赋值:
X x1,x2;
x1 = x2 = 42; // equivalent to `x2 = 42; x1 = x2;`
(x1 = x2) = 42; // equivalent to `x1 = x2; x1 = 42;`发布于 2012-02-07 03:46:03
也许,您的代码应该是这样的:
class X {
public:
int temp;
private :
//Some functions here
X &operator =(int z)
{
temp = z;
return *this ;
}
};然后你和operator=打交道,而不是和&operator打交道
您的operator =返回它所应用的对象的引用。
https://stackoverflow.com/questions/9166141
复制相似问题