簡體   English   中英

C++ 中的“error()”function 在我使用“#include”時有效<iostream> ',但不是'#include "std_lib_facilities.h"'</iostream>

[英]'error()' function in C++ works when I use '#include <iostream>', but not '#include "std_lib_facilities.h"'

我正在使用“使用 C++ 的編程原理和實踐”一書學習 C++ 的編程,而且我之前沒有任何編程經驗。 我正在使用 Visual Studio 2022(C++11、C++14、C++17)

在書的第五章,作者介紹了一個function,叫做'error()',它簡單地拋出一個runtime_error() function。我復制了書上的代碼作為例子,但是編譯器說“不止一個實例的重載 function 錯誤 ()”。 我使用的是作者為學習使用本書而准備的 header 文件std_lib_facilities.h 當我改為使用“#include”時,完全相同的代碼按預期運行。 為什么?

它給了我這個錯誤:

more than one instance of overloaded function "error" matches the
argument list, 'error': ambiguous call to overload function

這是代碼:

#include "std_lib_facilities.h" //it works when I use #include <iostream>
using namespace std;

void error(string s) {
throw runtime_error(s);
}

double some_function() {
double d; cin >> d;
if (!cin) error("couldn't read a double in 'some_function()'");
return 0;
}

int main() {
try {
    some_function();
}

catch (runtime_error& e) {
    cerr << "runtime error: " << e.what() << '\n';
}
return 0;
}

問題是您正在使用 using 指令

using namespace std;

這在全局命名空間中引入了標准的 function error ,用於不合格名稱查找和使用不合格名稱調用 function error 這導致模棱兩可。

例如,您應該使用限定名稱

if (!cin) ::error("couldn't read a double in 'some_function()'");
          ^^^^^^^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM