C++ 非常量引用函数重载
Posted
技术标签:
【中文标题】C++ 非常量引用函数重载【英文标题】:C++ nonconst-const reference function overloading 【发布时间】:2013-11-26 17:17:23 【问题描述】:在以下代码中:
int foo(const int& f) //version 1
int g = f;
return int(foo(g)); // calls itself, turning into SO
int& foo(int& f) //version 2
f *= -1;
return f;
int main()
int f = 11;
cout << foo(f) << endl;
cout << foo(22) << endl;
第一个 cout 按预期打印 -11; f 是一个 lvalue,所以它绑定到 foo 的第二个版本(虽然它也可以绑定到第一个版本,第二个版本更好匹配)。
foo
的第二次调用使用右值作为参数,因此foo
的唯一可行版本是第一个。到现在为止还挺好。在foo
的第一个版本中,我制作了参数的副本,这样我就可以调用第二个版本(带有lvalue)并在调用第二个版本的@ 之后返回它的副本987654325@。问题是这会变成堆栈溢出;仍然会调用foo
的第一个版本。
有人可以向我解释为什么会发生这种情况吗?我希望g
在foo
的第一个版本中作为参数传递时绑定到foo
的第二个版本。
【问题讨论】:
第一个foo
怎么知道第二个foo
?
【参考方案1】:
真的很简单 - foo
在这一点上仅表示 foo(const int& f)
。没有第二个选择。还没有。切换定义。或将它们分开:
int foo(const int& f);
int& foo(int& f);
int main()
int f = 11;
cout << foo(f) << endl;
cout << foo(22) << endl;
int foo(const int& f) //version 1
int g = f;
return int(foo(g)); // calls itself, turning into SO
int& foo(int& f) //version 2
f *= -1;
return f;
【讨论】:
【参考方案2】:foo 的第一个声明不知道第二个的存在。试试这个:
int foo(int& f);
int foo(const int& f) //version 1
int g = f;
return int(foo(g)); // calls itself, turning into SO
【讨论】:
【参考方案3】:当编译器到达该行时:
return int(foo(g))
它不知道你的重载版本 2。在文件顶部添加原型声明:
int foo(const int& f);
int& foo(int& f);
这样编译器就会知道版本 2 的存在,并且可以在调用 foo
时考虑它。
【讨论】:
以上是关于C++ 非常量引用函数重载的主要内容,如果未能解决你的问题,请参考以下文章