Candidate function not viable: 'this' argument has type 'const A', but method is not marked const
时间: 2024-02-02 10:03:11 浏览: 52
这是一个关于C++编程语言中成员函数的规则。当一个成员函数想要在一个`const`对象中被调用时,这个成员函数必须被标记为`const`,否则编译器会报错,提示该函数不可行。这是因为`const`对象只能访问其成员函数中不会修改对象状态的部分,而没有被标记为`const`的成员函数可能会修改对象的状态,因此无法被`const`对象调用。
相关问题
mainmenu.cpp:1519:25: No viable overloaded '=' qlist.h:163:15: candidate function not viable: 'this' argument has type 'const QList<qint32>' (aka 'const QList<int>'), but method is not marked const qlist.h:166:19: candidate function not viable: 'this' argument has type 'const QList<qint32>' (aka 'const QList<int>'), but method is not marked const
这个错误是因为你试图修改一个常量QList的元素,而常量对象的成员是不可被修改的。当你尝试给一个常量QList赋值一个新的QList时,会发生这个错误。
如果你想要清空一个常量QList的元素,可以使用`QList::clear()`函数,示例代码如下:
```cpp
const QList<int> myList = {1, 2, 3};
QList<int> emptyList;
myList = emptyList; // 这样会报错,不能给常量赋值
emptyList = myList; // 这样也会报错,不能修改常量QList的元素
emptyList.clear(); // 这样可以清空常量QList的元素
```
需要注意的是,清空常量QList的元素并不会释放其占用的内存空间,因为常量对象是只读的,所以不能对其进行内存的修改。如果你想要释放常量QList占用的内存空间,需要将其定义为非常量对象,并使用`QList::squeeze()`函数释放内存空间。
报错这个mainmenu.cpp:1519:25: No viable overloaded '=' qlist.h:163:15: candidate function not viable: 'this' argument has type 'const QList<qint32>' (aka 'const QList<int>'), but method is not marked const qlist.h:166:19: candidate function not viable: 'this' argument has type 'const QList<qint32>' (aka 'const QList<int>'), but method is not marked const
这个错误是因为你试图修改一个常量QList的元素,而常量对象的成员是不可被修改的。当你尝试给一个常量QList赋值一个新的QList时,会发生这个错误。
如果你想要清空一个常量QList的元素,可以使用`QList::clear()`函数,示例代码如下:
```cpp
const QList<int> myList = {1, 2, 3};
QList<int> emptyList;
myList = emptyList; // 这样会报错,不能给常量赋值
emptyList = myList; // 这样也会报错,不能修改常量QList的元素
emptyList.clear(); // 这样可以清空常量QList的元素
```
需要注意的是,清空常量QList的元素并不会释放其占用的内存空间,因为常量对象是只读的,所以不能对其进行内存的修改。如果你想要释放常量QList占用的内存空间,需要将其定义为非常量对象,并使用`QList::squeeze()`函数释放内存空间。