c++ - 一个奇怪的 C++ 错误 : test. cpp:15:错误:将 ‘const *’ 作为 ‘this’ 的 ‘*’ 参数传递会丢弃限定符

标签 c++ compiler-errors constants

我在处理一段特定的代码时遇到了一些问题,如果有人能在这件事上给我启发,我将不胜感激,我已在以下示例中隔离了问题:

#include <iostream>

using namespace std;

class testing{
   int test();
   int test1(const testing& test2);
};

int testing::test(){
   return 1;
}

int testing::test1(const testing& test2){
   test2.test();
   return 1;
}

那么可能导致以下错误:

test.cpp:15: 错误:将“const testing”作为“int testing::test()”的“this”参数传递会丢弃限定符

非常感谢!

最佳答案

问题是在 const 对象 test2 上调用非 const 函数 test2.test()来自 testing::test1.

testing::test1 获取 test2 作为参数 const testing &test2。所以在 testing::test1 中,test2const。然后在函数的第一行:

test2.test()

testing::test 函数在 test2 上调用。该函数未在签名末尾使用 const 声明,因此它可能会修改调用它的对象(this 指针隐式传递给它),即使它没有,编译器假设是这样。通过让您在那里调用它,编译器将允许您修改 const 变量而无需显式转换,这是 C++ 不应该允许的。 因此解释错误信息:

test.cpp:15: error: passing ‘const testing’ as ‘this’ argument of ‘int testing::test()’ discards qualifiers

this 指的是成员函数(testing::test)操作的对象,在这种情况下它不是const,因为 testing::test 没有用 const 声明,因此在尝试创建非 const 指针(this) 引用 const 对象 (testing),忽略 const 限定符

要解决这个问题,请确定 testing::test 函数是否需要修改调用它的对象(现在的编写方式不需要,因为它所做的只是 return 1,但是这可能会改变,所以你需要考虑它的预期功能是什么)。如果应该这样,那么显然在 const 对象上调用它是不好的,尽管您可以使用 const_cast 要求编译器覆盖它,但这很危险。如果不应该,则将其标记为 const,以便也可以在 const 对象上调用它:

class testing{
    int test1() const;
    // ...
}

int testing::test() const {
    // ...
}

关于c++ - 一个奇怪的 C++ 错误 : test. cpp:15:错误:将 ‘const *’ 作为 ‘this’ 的 ‘*’ 参数传递会丢弃限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/550428/

相关文章:

c++ - 在 C 中捕获 & 和 && 误用的技巧?

c - 传递结构指针的问题和 "conflicting types"错误

r - 在Windows R中设置C编译器(CC)

go - 为什么在 golang 中不断逃逸到堆中?

c++ - 如何为需要所有常量值的方法提供参数?

c++ - 如何在命令后保持我的 shell 运行

c++ - Visual 2010 中带有 lambda 函数和枚举的 C2665,是错误还是正常?

c++ - 错误 : invalid initialization for struct in C++

c++ - 将 vector <bool> 转换为 int

c++ - 前向声明未按预期工作