开发者

Vector of custom objects : Assign compilation failure

开发者 https://www.devze.com 2023-02-10 00:18 出处:网络
I am creating a vector of custom objects and calling assign as follows: class myClass { public: myClass() { cout<<\"MyClass def const\"<<endl; }

I am creating a vector of custom objects and calling assign as follows:

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;
}

Relevant compilation errors:

/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&)

I am not sure what i am missing since i have overloaded the = operator.

Edit :

It seems my signature was wrong as corrected below. As i understand the valid signatures are:

(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 ); 

Where is the restriction to pass argument as a const reference defined?


The argument for the assignment operator must be const, e.g.

myClass& operator=(const myClass &mclass)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号