Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Use of plus() is ambiguous" error

Tags:

c++

function

add

I am trying to write a function which takes two numbers and prints out 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 I get:

use of `plus' is ambiguous

It´s my first C++ program and in fact I am getting blind finding an error.

like image 910
Jac08H Avatar asked Jul 23 '15 16:07

Jac08H


2 Answers

Either do

result = ::plus(a,b);

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

like image 53
yizzlez Avatar answered Oct 30 '22 20:10

yizzlez


There is already a function object in the std namespace called plus. Because of using namespace std; this std::plus is put in the global namespace, which is also where your plus() is named. When you attempt to call your plus() the compiler can't tell whether you are referring to std::plus or your plus() because they are both in the global namespace.

You have the following options:

  1. Remove using namespace std; (you'll then need to qualify other functions in the std namespace -- e.g. std::cout).
  2. Put your plus() in its own namespace (say, mine), and call it using mine::plus(a, b).
  3. Call your function with ::plus() as suggested (assuming you don't put it in its own namespace).
  4. Rename the function so that there is no name collision.
like image 28
Null Avatar answered Oct 30 '22 20:10

Null