error: passing ‘const Array’ as ‘this’ argument discards qualifiers [-fpermissive]
时间: 2023-09-21 17:02:56 浏览: 72
这个错误通常出现在你试图使用一个 const 对象调用一个非 const 的成员函数时。在 C++ 中,当你声明一个对象为 const 时,意味着你不能修改它的成员变量。因此,编译器会阻止你调用这个对象的非 const 成员函数,以保证对象的状态不被改变。
例如:
```
class MyClass {
public:
void modify() {
// do something to modify the object
}
void display() const {
// do something to display the object
}
};
int main() {
const MyClass obj;
obj.modify(); // Error: modifying a const object
obj.display(); // OK: const member function
return 0;
}
```
在上面的代码中,我们声明了一个 const 的 MyClass 对象 `obj`。因为 `obj` 是 const 的,所以我们不能调用它的非 const 成员函数 `modify()`,但我们可以调用它的 const 成员函数 `display()`。
如果你需要在 const 对象上调用非 const 成员函数,你可以将成员函数声明为 const。例如:
```
class MyClass {
public:
void modify() const {
// do something to modify the object
}
void display() const {
// do something to display the object
}
};
int main() {
const MyClass obj;
obj.modify(); // OK: const member function
obj.display(); // OK: const member function
return 0;
}
```
在上面的代码中,我们将 `modify()` 成员函数声明为 const,这样就可以在 const 对象上调用它了。