gpt4 book ai didi

c++ - 基于 L 值与 R 值的重载

转载 作者:搜寻专家 更新时间:2023-10-31 01:04:40 25 4
gpt4 key购买 nike

我在一本 C++ 书中发现了以下内容:

Although we will not be doing it in this book, you can overload a function name (or operator) so that it behaves differently when used as an l-value and when it is used as an r-value. (Recall that an l-value means it can be used on the left-hand side of an assignment statement.) For example, if you want a function f to behave differently depending on whether it is used as an l-value or an r-value, you can do so as follows:

class SomeClass { 
public:
int& f(); // will be used in any l-value invocation const
const int& f( ) const; // used in any r-value invocation ...
};

我试过了,没用:

class Foo {
public:
int& id(int& a);
const int& id(int& a) const;
};

int main() {
int a;
Foo f;
f.id(a) = 2;
a = f.id(a);
cout << f.id(a) << endl;
}

int& Foo :: id(int& a) {
cout << "Bar\n";
return a;
}

const int& Foo :: id(int& a) const {
cout << "No bar !\n";
return a;
}

我是不是理解错了?

最佳答案

要么书中的示例完全错误,要么您从书中复制了错误的示例。

class SomeClass { 
public:
int& f(); // will be used in any l-value invocation const
const int& f( ) const; // used in any r-value invocation ...
};

使用这段代码,当您调用 s.f() 时,其中 sSomeClass 类型的对象,第一个版本将在s 是非const,当sconst 时将调用第二个版本。值类别与它无关。

Ref 资格看起来像这样:

#include <iostream>
class SomeClass {
public:
int f() & { std::cout << "lvalue\n"; }
int f() && { std::cout << "rvalue\n"; }
};
int main() {
SomeClass s; s.f(); // prints "lvalue"
SomeClass{}.f(); // prints "rvalue"
}

关于c++ - 基于 L 值与 R 值的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23477568/

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