us...">

Msgstr "Using the plus () error is ambiguous"

I am trying to write a function that takes two numbers and prints their sum.

#include <iostream> using namespace std; int plus(int, int); int main () { int a, b, result; cout << "2 numbrs"; cin>>a>>b; result = plus(a,b); cout << result; return 0; } int plus(int a,int b) { int sum; sum = a+b; return sum; } 

and error:

 use of `plus' is ambiguous 

This is my first C ++ program, and in fact I am getting blind when I find an error.

+7
c ++ function add
source share
2 answers

Or do

 result = ::plus(a,b); 

Or rename the function. This is a good lesson why using namespace std not considered good practice.

+19
source share

There is already a function object in std namespace called plus . Due to using namespace std; this std::plus is placed in the global namespace, which is also called your plus() . When you try to call your plus() , the compiler cannot determine whether you are referencing std::plus or your plus() because they are both in the global namespace.

You have the following options:

  • Delete using namespace std; (then you will need to qualify other functions in the std - for example, std::cout ).
  • Put your plus() in your own namespace (e.g. mine ) and call it with mine::plus(a, b) .
  • Call your function with ::plus() as suggested (assuming you don't put it in your own namespace).
  • Rename the function so that there are no name clashes.
+14
source share

All Articles