简体   繁体   中英

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

I am learning programming with C++ using the book "Programming Principles and Practices Using C++", and I have no prior programming experience whatsoever. I'm using Visual Studio 2022 (C++11, C++14, C++17)

In chapter 5 of the book, the author introduces a function called 'error()', which simply throws a runtime_error() function. I copied the code in the book for an example, but the compiler says "more than one instance of the overloaded function error()". I was using the header file the author prepared for the purpose of learning using the book, std_lib_facilities.h . When I instead used "#include ", the exact same code ran as intended. Why?

It gives me this error:

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

This is the code:

#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;
}

The problem is that you are using the using directive

using namespace std;

that introduces the standard function error in the global namespace for unqualified name-lookup and using unqualified names to call the function error . That results in umbiguous.

You should use a qualified name as for example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM