C++代码中'triangle'调用存在歧义错误的技术问询
搞定C++递归函数的调用歧义问题
嘿,我来帮你解决这个call to 'triangle' is ambiguous的错误!
错误根源分析
你遇到的这个歧义错误,核心问题是命名空间冲突:
- 你代码里写了
using namespace mry2270;,而这个命名空间里大概率已经存在一个和你自己定义的triangle同名的函数。 - 编译器在处理
triangle(outs, ++m, n);这类调用时,完全搞不清你要调用的是自己写的那个triangle,还是mry2270命名空间里的同名函数,所以直接抛出了歧义错误。
另外你的代码还有两个小细节需要修复:
- 没包含
<iostream>头文件,cout和ostream都是这个头文件里的东西,必须加上。 main函数的参数里cons...明显是笔误,应该是const char* argv[]。
两种修复方案
方案1:别直接引入整个命名空间(推荐)
日常开发里最好别用using namespace xxx;这种写法,很容易踩命名冲突的坑。我们可以改用命名空间限定符,或者只引入需要的成员:
#include <iostream> // 补上缺失的头文件 #include "rec_fun.h" // 去掉using namespace mry2270; 改用限定符访问命名空间内容 void triangle(std::ostream& outs, unsigned int m, unsigned int n){ if (m <= n){ for (int i = 0; i < m; i++){ std::cout << "*"; // 用std::限定cout } std::cout << std::endl; triangle(outs, ++m, n); // 这里调用的是自己定义的全局函数,无歧义 } else if (m > n && n >= 0) { for (int i = 0; i < n; i++){ std::cout << "*"; } std::cout << std::endl; triangle(outs, m, --n); } } void numbers(std::ostream& outs, const std::string& prefix, unsigned int levels){ // 这里补充你的函数实现 } bool bears(int n){ return 0; } int main(int argc, const char* argv[]){ // 修复main的参数错误 // 举个测试例子 triangle(std::cout, 1, 3); return 0; }
方案2:明确指定函数的作用域
如果你一定要保留using namespace mry2270;,那就在调用自己的triangle时加上全局作用域符::,告诉编译器"我要调用的是全局命名空间下的这个函数":
#include <iostream> #include "rec_fun.h" using namespace mry2270; void triangle(std::ostream& outs, unsigned int m, unsigned int n){ if (m <= n){ for (int i = 0; i < m; i++){ std::cout << "*"; } std::cout << std::endl; ::triangle(outs, ++m, n); // 用::指定全局作用域的triangle,避免歧义 } else if (m > n && n >= 0) { for (int i = 0; i < n; i++){ std::cout << "*"; } std::cout << std::endl; ::triangle(outs, m, --n); } } // 其他函数和main的修复同上
小提示
- 以后写代码尽量避免
using namespace std;或者其他整命名空间引入的写法,能大幅减少这类命名冲突问题。 - 你可以打开
rec_fun.h看看mry2270命名空间里的内容,确认一下是不是真的有个同名的triangle函数,这样能更清楚冲突的来源。
内容的提问来源于stack exchange,提问作者Caique Morais Melo Costa
相关产品推荐
相关产品推荐

