什么是“错误:传递'const String'作为'this'参数丢弃限定符[-fpermissive]”是什么意思?

时间:2016-11-01 02:27:09

标签: arrays string char

我试图找出解决方案并研究过一个,但仍未找到解决方案。

我的String.cpp收到了这个错误:

error: passing ‘const String’ as ‘this’ argument discards qualifiers [-fpermissive]
if(_length != two.length())
                         ^
String.cpp:59:5: note:   in call to ‘int String::length()’
int String::length()

String.cpp: In member function ‘bool String::add(const String&) const’:
String.cpp:115:32: error: passing ‘const String’ as ‘this’ argument discards qualifiers [-fpermissive]
for(int i = 0; i < two.length(); i++)
                              ^
String.cpp:59:5: note:   in call to ‘int String::length()’
int String::length()
     ^
String.cpp:116:15: error: increment of member ‘String::_length’ in read-only object
data[_length++] = two.at(i);
            ^
String.cpp:116:29: error: passing ‘const String’ as ‘this’ argument discards qualifiers [-fpermissive]
data[_length++] = two.at(i);
                         ^
String.cpp:76:6: note:   in call to ‘char String::at(int)’
char String::at(int index)

我真的不知道如何解决它?

这是我的String.cpp:

bool String::equal(const String &two) const
{
if(_length != two.length())
    return false;
    for(int i = 0; i < _length; i++)
        if(data[i] != two.at(i))
        return false;
    return true;   
}

bool String::add(const String &two) const
{
for(int i = 0; i < two.length(); i++)
    data[_length++] = two.at(i);
    data[_length] = '\0';
return true;
}

这是我的String.h文件:     {     私人:

    int _length;
    char *data;
    int getCharArraySize(char arr[]);

public:

    String();
    String(char str[]);
    String(const String &);
    virtual ~String(); //Destructor should delete your data pointer.

    int length();
    void clear(); 
    bool empty();
    char at(int index);
    int find(char substr[], int startIndex);
    bool equal(const String &) const;
    bool add(const String &) const;
    void print() const;

    void operator<<(const String &) const;
    bool operator==(const String &) const; //Should replace your equal() method. 
    bool operator+(const String &) const; //Should replace your add()    method. Should append the char* in two to the object doing the         calling. Return true if you were able to add the two together, false if not. 
    void operator=(const String &) const; //Should assign two to the calling object. 
    char operator[](int index) const; //Should replace your at() method. 



 };

1 个答案:

答案 0 :(得分:1)

您的lengthatemptyfind方法都应该是常量。此外,您的add函数不应该是常量。