关于R值
#include <iostream>
#include <ctime>
#include <chrono>
#include "Person.h"
#include "SmartPerson.h"
using namespace std;
void print_name(const Person& test);
void print_name_2(const Person&& test);
int main()
{
print_name(Person{ 21, "Juan", "Hispanic" });
return 0;
}
void print_name(const Person& test)
{
cout << "L value!" << endl;
cout << test.get_name() << endl;
}
void print_name_2(const Person&& test)
{
cout << "R value!" << endl;
cout << test.get_name() << endl;
}
在上述情况下,为什么调用函数 print_name 而不是 print_name_2 ?即使传递的是 R 值?我还想知道,引用常量 R 值的目的是什么。
#include <iostream>
#include <ctime>
#include <chrono>
#include "Person.h"
#include "SmartPerson.h"
using namespace std;
void print_name(const Person& test);
void print_name_2(const Person&& test);
int main()
{
print_name(Person{ 21, "Juan", "Hispanic" });
return 0;
}
void print_name(const Person& test)
{
cout << "L value!" << endl;
cout << test.get_name() << endl;
}
void print_name_2(const Person&& test)
{
cout << "R value!" << endl;
cout << test.get_name() << endl;
}
Why is the function print_name called instead of print_name_2 in the above case? Even though it was an R-value being passed? I also want to know, what the purpose of a reference to a constant R-value is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的意思是
print_name
和print_name_2
是同一函数的重载吗?无论传递什么参数,编写print_name
都不会调用print_name_2
。将两个函数更改为具有相同的名称将导致按预期调用右值版本: https://godbolt.org /z/PdvEe768z。
Did you mean for
print_name
andprint_name_2
to be overloads of the same function? Writingprint_name
will never invokeprint_name_2
no matter the arguments that are passed.Changing both functions to have the same name will cause the rvalue version to be called as expected: https://godbolt.org/z/PdvEe768z.