无法转换'this'指针...遗产

cannot convert 'this' pointer... inheritance

本文关键字:指针 遗产 this 转换      更新时间:2023-10-16

尝试从继承类调用函数string SetToString(StringSet aSet);时出错。基类的头文件:

#ifndef ITEM_H
#define ITEM_H
#include <ostream>
#include <set>
#include <string>

using namespace std;
typedef set<string> StringSet;
class Item
{
protected:
    string  title;
    StringSet keywords;
public:
    Item();
    Item(const string& title, const string& keywords);
    virtual ~Item();
    void addKeywords(string keyword);
    virtual ostream& print(ostream& out) const;
    string getTitle() const;
    string SetToString(StringSet aSet);
};

基类的实现文件:

#include "Item.h"
...
string Item::SetToString(StringSet aSet) {
    string key;
    int sizeCount = 0;
    for (auto const& e : aSet) {
        key += e;
        sizeCount++;
        if (sizeCount < aSet.size()) {
            key += ", ";
        }
    }
    SetToString(keywords);
    return key;
}
...

当我尝试在继承的类中执行string k = SetToString(keywords);时,我会得到错误:Error C2662 'std::string Item::SetToString(StringSet)': cannot convert 'this' pointer from 'const Book' to 'Item &'。如何修复这个错误,为什么我会得到它?

Item::SetToString未标记为const,因此无法通过const指针或引用或在const对象上调用。

您似乎试图从一个标记为const的函数中调用它,因此该函数无法修改当前对象(this),包括调用其上的非const函数。

要么使继承的函数不是const,要么使基函数成为const