2011-11-15 105 views

回答

0

看到您可以定义任何类型的运算符=()的。即使是非常无用的。但是它们中的不会被继承到子类。从你的链接网站上,我稍微改变了一下这个例子,使其更加清晰。由于提到的错误,此示例不会编译。

class mother { 
public: 
    mother() 
    { cout << "mother: no parameters\n"; } 
    explicit mother (int a):m_int(a) 
    { cout << "mother: int parameter\n"; } 

    mother& operator=(mother const& rhs) 
    { 
     if(&rhs != this) 
     { 
      m_int = rhs.m_int; 
     } 
     return *this; 
    } 

    mother& operator=(int i) 
    { 
     m_int = i; 
     return *this; 
    } 
private: 
    int m_int; 
}; 

class son : public mother { 
public: 
    explicit son (int a) : mother (a) 
    { cout << "son: int parameter\n\n"; } 
}; 
int main() 
{ 
    mother mom(2); 
    son daniel(0); 
    mom = 3; 
    daniel = 4; // compile error 
    daniel = mom; // also error 
} 
2

operator=()是赋值运算符。通过在“成员”上具有复数形式,这意味着所有的赋值运算符过载(例如,+=,*=等)。

+2

我怀疑复数也可能意味着'operator ='的多重过载。 –

+1

值得注意的是,这个列表对于C++ 98来说只是部分正确的。在C++ 98中,构造函数不是继承的(而'operator ='是继承的,但是会自动映射)。在C++ 11中,必须区分不包含构造函数的普通继承和通过'using'显式构造函数继承。 –

1

它可以赋值操作符Object& operator=(const Object& rhs)和传输运营商Object& operator=(Object& rhs),与智能指针等

0

operator=()是类赋值运算符,如果你希望能够轻松地分配值表格类其他的一个对象,而不必通过porcess到繁琐步骤每一次它被定义。这个过程被称为overloading,维基百科有一个覆盖该主题的great article,与C++ documentation一样。