返回的值必须与函数的返回类型具有相同的类型? [英] The value returned must have the same type as the function return type?
问题描述
具有返回类型(非void)的函数中的每个返回都必须
返回一个值。返回的值必须与
函数的返回类型具有相同的类型,或者必须具有可以隐式地将
转换为该类型的类型。- C ++ Primer
struct Person
{
const std::string & getName() const { return name; }
std::string name;
};
问:在函数 getName()
中,返回的值与函数返回类型具有相同的类型吗?
Q: In function getName()
, does the valued returned have the same type as the function return type?
推荐答案
const std::string & getName() const { return name; }
此函数向名称返回 reference
。
This function returns a reference to name
.
引用是一种简单的引用数据类型,其功能不如从C继承的指针类型强大,但更安全。在C ++中,引用的定义是这样的,它不需要存在。可以将其实现为现有对象的新名称(类似于Ada中的重命名关键字)。
A reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C. The definition of a reference in C++ is such that it does not need to exist. It can be implemented as a new name for an existing object (similar to rename keyword in Ada).
有关更多详细信息,请参见: https://en.wikipedia.org/wiki/Reference_(C%2B %2B)
For more details, see: https://en.wikipedia.org/wiki/Reference_(C%2B%2B)
这篇关于返回的值必须与函数的返回类型具有相同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!