我正在创建一个自定义对象的向量,并按如下方式调用assign:
class myClass
{
public:
myClass() { cout<<"MyClass def const"<<endl; }
myClass(const myClass &mclass) {cout<<"Default const"<<endl;}
myClass& operator=(myClass &mclass) { cout<<"called overloaded = operator"<<endl; return mclass; }
};
int main()
{
myClass m;
cout<<"orginal object:"<<endl;
vector<myClass> vec1,vec2,vec3;
vec1.assign(10,m);
return 0;
}
相关编译错误:
/usr/lib/gcc/i386-redhat-linux/4.3.2/../../../../include/c++/4.3.2/bits/stl_vector.h:344: instantiated from ‘void std::vector<_Tp, _Alloc>::assign(size_t, const _Tp&) [with _Tp = myClass, _Alloc = std::allocator<myClass>]’
test.cpp:52: instantiated from here
/usr/lib/gcc/i386-redhat-linux/4.3.2/../../../../include/c++/4.3.2/bits/stl_algobase.h:686: error: no match for ‘operator=’ in ‘* __first = __value’
test.cpp:43: note: candidates are: myClass& myClass::operator=(myClass&)
我不知道我错过了什么,因为我重载了=运算符。
编辑:
我的签名似乎错误如下所述。据我所知,有效签名是:
(1) MyClass& operator=( const MyClass& rhs );
(2) MyClass& operator=( MyClass& rhs );
(3) MyClass& operator=( MyClass rhs );
(4) const MyClass& operator=( const MyClass& rhs );
(5) const MyClass& operator=( MyClass& rhs );
(6) const MyClass& operator=( MyClass rhs );
(7) MyClass operator=( const MyClass& rhs );
(8) MyClass operator=( MyClass& rhs );
(9) MyClass operator=( MyClass rhs );
将参数作为const引用定义的限制在哪里?
答案 0 :(得分:4)
赋值运算符的参数必须为const
,例如
myClass& operator=(const myClass &mclass)