注册 登录
编程论坛 C++教室

vector& operator=(const vector&); 求解释

czyhzc 发布于 2012-03-15 15:06, 2432 次点击
class vector {
    int sz;
    double* elem;
    void copy(const vector& arg);     // copy elements from arg into *elem
public:
    vector(int s) :sz(s), elem(new double[s]) { } // constructor
    ~vector() { delete[] elem; }                  // destructor
   // int size() const { return sz; }               // the current size
    double get(int n) { return elem[n]; }         // access: read
    void set(int n, double v) { elem[n]=v; }      // access: write
    vector& operator=(const vector&);            
};
请问各位vector& operator=(const vector&); 这句从语法上怎么解释,谢谢
5 回复
#2
BianChengNan2012-03-15 15:10
就是把一个vector赋值给另外一个呀,用引用是因为效率。const是因为防止被意外改变。
#3
czyhzc2012-03-15 15:24
vector& vector::operator=(const vector& a)
// make this vector a copy of a
{
    double* p = new double[a.sz];     // allocate new space
    copy(a);                          // copy elements
    delete[ ] elem;                   // deallocate old space
    elem = p;                         // now we can re-set elem
    sz = a.sz;
    return *this;                     
}
这样可以吗?
#4
czyhzc2012-03-15 15:27
vector& operator=(const vector&); 那此时的operator只是一个vector&的变量,那它怎么又可以定义啊???
#5
榴紫丫2012-03-15 20:42
这个是在 vector 类中  对  = 运算符加载(operator)函数的说明,const vector&);
是对类vector成员引用作为,而返回值也是类的成员vector&
#6
BianChengNan2012-03-17 12:32
以下是引用czyhzc在2012-3-15 15:24:29的发言:

vector& vector::operator=(const vector& a)
// make this vector a copy of a
{
    double* p = new double[a.sz];     // allocate new space
    copy(a);                          // copy elements
    delete[ ] elem;                   // deallocate old space
    elem = p;                         // now we can re-set elem
    sz = a.sz;
    return *this;                     
}
这样可以吗?
可以,但是不好。
最好在函数的开始加上是不是赋值给自身的判断,如果是直接返回
if(this == &a) return *this;
1