gpt4 book ai didi

c++ - 在 C++ 中的 const 实例上调用非 const 函数,这可能吗?

转载 作者:行者123 更新时间:2023-11-28 01:38:29 25 4
gpt4 key购买 nike

我有下面这段代码,

#include <iostream>
#include <string>
using namespace std;

class Foo {
public:
void print() { cout << "hello\n"; }
}
;

Foo get_foo() {
Foo f;

return f;
}
int main()
{
// If I get rid of this "const", then the error goes away
const Foo f = get_foo();

f.print();

return 0;

}

当我编译这个时,它给了我这个错误

test.cc:21:11: error: passing ‘const Foo’ as ‘this’ argument discards qualifiers [-fpermissive]                                
f.print();

我尝试在 f 的声明中删除“const”,然后代码会编译。

但是我不明白这个限制。有人可以解释一下吗?如何在不从字段声明中删除“const”的情况下调用“print()”?

编辑:上面添加的“Foo”类纯粹是为了演示目的。在我的真实代码中,我无法编辑该类,但我想将“f”设为常量的原因是出于代码样式/安全原因。

最佳答案

The "Foo" class added above is purely for demonstrative purpose. In my real code, I can't edit the class, but the reason I want to make "f" const is for code-style/safety reason.

void print() { cout << "hello\n"; }

没有被声明为 Fooconst 成员函数,你不能改变它,你将不得不接受那个糟糕的设计,并访问 >print() 函数通过非 const 实例或引用。

要做到这一点,需要在 Foo 类中声明 print()

void print() const { cout << "hello\n"; }
// ^^^^^

我同意更好的代码风格是允许使用 Foo 的 const 实例调用 print() 函数

但是正如您所提到的,如果您不能更改它,那么除了使用显式转换之外别无他法:

const_cast<Foo&>(f).print();

无论如何,与简单调用相比,不会增加额外的“安全”:

int main()
{
Foo f = get_foo();
f.print();
}

关于c++ - 在 C++ 中的 const 实例上调用非 const 函数,这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48331942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com