gpt4 book ai didi

c++ - Const 和引用成员函数限定符

转载 作者:行者123 更新时间:2023-12-02 08:07:32 24 4
gpt4 key购买 nike

假设我们有一个成员类,其中两个成员函数定义如下:

class SomeClass
{
private:
int val = {};
public:

const int getVarLRef() & {
return val;
}
const int getVarCLRef() const& {
return val;
}
};

int main()
{
auto var1 = SomeClass().getVarCLRef();
auto var2 = SomeClass().getVarLRef();
return 0;
}

我不太明白const&&之间有什么区别。如果我们将此函数指定为 const&,为什么它可以与 getVarCLRef 一起使用?难道不应该只允许使用左值调用它吗?

另一方面,

getVarLRef 工作得很好,但在这种情况下无法按预期进行编译。

I use C++11 and gcc 7.3.0

最佳答案

Const 和引用成员函数限定符能够将这些限定符应用于“this”,就像常规参数一样,因此主要是:

int getVarLRef(SomeClass& self) { return self.val; }
int getVarCLRef(const SomeClass& self) { return self.val; }

我想你知道:

getVarCLRef(SomeClass()); // Valid, temporary can bind to const lvalue reference
getVarLRef(SomeClass()); // INVALID, temporary CANNOT bind to non-const lvalue reference

关于c++ - Const 和引用成员函数限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59101854/

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