简体   繁体   中英

const and not const in copy constructor?

When I wrote my copy constructor that: (HocSinh is a class)

HocSinh::HocSinh(HocSinh &a)
{
    hoTen = a.hoTen;
    diemVan = a.diemVan;
    diemToan = a.diemToan;
}

then:

HocSinh hocSinh("abc", 1, 2);
vector <HocSinh> dsHSCanTim;
dsHSCanTim.push_back(hocSinh);

I got an error: "no copy constructor available or copy constructor is declared 'explicit'". But when I wrote:

HocSinh::HocSinh(const HocSinh &a)
{
    hoTen = a.hoTen;
    diemVan = a.diemVan;
    diemToan = a.diemToan;
}

There was no error. Can someone explain this for me please. Thank everyone and sorry if my English is so bad.

Because std::vector::push_back is defined as

void push_back (const value_type& val);
void push_back (value_type&& val);

For an lvalue like hocSinh , the std::vector::push_back template would use the first one. Inside std::vector::push_back implementation, a copy constructor is used to construct the object in the memory segment allocated by std::vector . The implementation has to use const value_type& val as the source of this copy, so it needs a copy constructor with a const signature to take val .

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