作为返回类型"const int&"做什么?
What does "const int&" do as a return type?
const int& max(int a[], int length)
{
int i=0;
for(int j=0; j<length; j++)
if(a[j]>a[i]) i=j;
return a[i];
}
int main(){
int array[] = {12, -54, 0, 123, 63};
int largest;
largest = max(array,5);
cout<< "Largest element is " << largest << endl;
return 0;
}
所以我的问题是," const int&amp;作为返回类型?为什么我在函数期望参考时返回值?
通常,返回参考可以避免复制返回值,并且(如果不是 const
qualified(使您有机会更改"原始"值。返回类型const T&
通常与类类型的对象结合使用,例如std::vector
,复制可能导致(不需要的(开销。但是,与int
这样的基本数据类型结合使用,传递const int&
可能比复制原始INT值更开销。
此外,在您的示例中,如果将const int&
类型的结果分配给非参考类型,例如 int largest = max(...)
,返回值是"重新推荐"的,并按值分配。因此,您可以更改变量的内容,因为它是const
参考值的副本。如果您具有const int&
类型,并且将其分配给类型const int&
的变量,则可以获得参考,但是编译器将不允许您更改其内容。
因此,唯一没有int
引用的内容是没有const
,然后您将允许您更改" Origninal"值的内容。请参阅以下代码;希望它有所帮助:
int& max(int a[], int length) {
return a[3];
}
const int& maxConst(int a[], int length) {
return a[3];
}
int main(){
int array[] = {12, -54, 0, 123, 63};
int largest = max(array,5);
cout<< "Largest element (value) is " << largest << endl;
largest = 10;
cout << "Element at pos 3 is: " << array[3] << endl;
int largestConst = maxConst(array,5);
cout<< "Largest element (value) is " << largestConst << endl;
largestConst = 10;
cout << "Element at pos 3 is: " << array[3] << endl;
int &largestRef = max(array,5);
cout<< "Largest element (ref) is " << largestRef << endl;
largestRef = 10;
cout << "Element at pos 3 is: " << array[3] << endl;
const int &largestRefConst = maxConst(array,5);
cout<< "Largest element (value) is " << largestRefConst << endl;
// largestRefConst = 10; // -> cannot assign to variable with const-qualified type
//cout << "Element at pos 3 is: " << array[3] << endl;
return 0;
}
输出:
Largest element (value) is 123
Element at pos 3 is: 123
Largest element (value) is 123
Element at pos 3 is: 123
Largest element (ref) is 123
Element at pos 3 is: 10
Largest element (value) is 10
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 在C++17中,引用const字符串的语义应该是什么
- 违反const正确性:我应该现实地期待什么问题
- 如果我在 const 函数上使用指针,我可以返回什么?
- 在只读(即 const)访问器上执行结构化绑定的最佳实践是什么?
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- "char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {"剂量是什么意思
- 语法问题:"char [5] const &"是什么意思?
- 有什么陷阱用 constexpr string_view 替换全局 const char[]?
- 在什么情况下,使用'const T*'输入参数比'const T&'更可取?
- 在 c++ 中,char *p 和 const char * p 有什么区别?
- 'note: 候選人: Volume& Volume::operator=(const Volume&)'.这个错误是什么?
- 有什么理由在函数中使用 const 吗?
- C++:在函数参数的上下文中,"const T &"和"T &&"有什么区别?
- 在下面函数的返回中添加 const 限定符的重要性是什么?
- 明确定义'static const variable in a struct'对C++ 11 及以上有什么影响吗?
- int(int)& 或 int(int) const &是什么类型?
- 这个(const vector<vector<int> > &A)"代码段是什么意思?