小飞将 2019-10-06 16:06 采纳率: 66.7%
浏览 378

error: passing ‘const HasPtr’as‘this’argument of‘HasPtr& HasPtr::operator=(const HasPtr&)’discards qualifiers [-fpermissive]

如题:
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类型对吗?

  • 写回答

1条回答 默认 最新

  • zqbnqsdsmd 2019-10-06 16:51
    关注
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型