如题:
HasPtr.h
#include <iostream>
#include <string>
class HasPtr {
public:
HasPtr(const std::string &s, int a)
: ps(new std::string(s)), i(a) {}
HasPtr(const std::string &s = std::string())
: ps(new std::string()), i(0) {}
HasPtr(const HasPtr &obj)
: ps(new std::string(*obj.ps)), i(obj.i) {
std::cout << "Copy constructor execute" << std::endl;
}
HasPtr & operator=(const HasPtr &rhs) {
ps = new std::string(*rhs.ps);
i = rhs.i;
return *this;
}
~HasPtr() {
delete ps;
}
std::string get_str() const {
return *ps;
}
int get_i() const {
return i;
}
bool operator<(const HasPtr obj) const {
return i < obj.i;
}
friend void swap(HasPtr &lhs, HasPtr &rhs) {
std::swap(lhs.ps, rhs.ps);
std::swap(lhs.i, rhs.i);
}
private:
std::string *ps;
int i;
};
main.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include "HasPtr.h"
int main() {
size_t n = 3;
std::vector<HasPtr> v;
for (size_t i = 0; i < n; ++i) {
v.push_back(std::to_string(i));
}
sort(v.cbegin(), v.cend());
}
遇到错误:
error: passing ‘const HasPtr’ as ‘this’ argument of ‘HasPtr& HasPtr::operator=(const HasPtr&)’ discards qualifiers [-fpermissive]
之前搜索的大多数答案是成员函数不是const类型的。但是我的问题处在拷贝赋值运算符上,没有理由要把拷贝赋值运算符也写成const类型对吗?