简体   繁体   中英

C++ vector compile error, when using vector::push_back() method

I'm using std::vector in my program and I get this error when compiling:

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc: In member function `User& User::operator=(const User&)':

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc:238: instantiated from void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = User, _Alloc = std::allocator<User>]' /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_vector.h:564: instantiated from void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = User, _Alloc = std::allocator]'

main.cpp:100: instantiated from here

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc:238: error: non-static const member `const std::string User::NAME', can't use default assignment operator

I have classes "User" and "Users":

class User {
    public:
        const string NAME;

        User(const string &name, const bool &isMain = false) : NAME(name), isMain(isMain) {};
        void addFollower(User * user);
        void addReplier(User * user, const int &count);
        void addMentioner(User * user, const int &count);
        void addRetweeter(User * user, const int &count);

    private:
        vector<User *> followedBy, repliedBy, mentionedBy, retweetedBy;
        vector<int> replyCount, mentionCount, retweetCount;
        bool isMain;
    };


class Users {
    public:
        vector<User> users;

        void addUser(const string &name, bool isMain = false);
        User * findUser(const string &name);
        friend ostream & operator <<(ostream &outStream, const Users &users);
        User & operator [] (unsigned int index);
    };

Here is the thing. The error is caused by the method Users::addUser():

void Users::addUser(const string &name, bool isMain) {
    User newUser(name, isMain);
    users.push_back(newUser);
}

If I erase the second line

users.push_back(newUser);

it works fine, but well, it doesn't work as like as you see because it prevents me from adding new records into the "users" vector array. I'll be thankful if anyone tells me what is the cause. Thanks

You have to provide a copy-constructor in order to use push_back , since your class contains a non-static const member.

You could fix this easily by using a getter instead:

class User{
public:
    string NAME() const { return m_name; }
    /* ... */
private:
    string m_name;
    /* ... */
};

大多数情况下,编译器会为您提供一个复制赋值运算符,但由于您有一个const成员变量,因此编译器无法执行此操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM