0

I'm writing a program with xcode to do some statistical analysis. However, when I'm building the function for computing the sample variance, xcode keeps telling me that my call the function sample_mean (which is also function defined by me) is ambiguous.

Here's the code:

#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>


//sample_mean
double sample_mean (std::vector<double> v);


//sample_variance
double sample_variance (std::vector<double> v);



int main()
{
    std::cout<<"hello world";
}


//sample_mean
double sample_mean (const std::vector<double>& v)
{
    double sum= 0;
    int i=0; for (; i<v.size(); ++i)
    {
        sum= sum+ v[i];
    }
    return sum/v.size();
}



//sample_variance
double sample_variance (const std::vector<double>& v)
{
    double average= sample_mean(v);
    double sum=0;
    int i=0; for (; i<v.size(); ++i)
    {
        sum= sum+ std::pow((v[i]-average), 2);
    }
    return sum/v.size();
}

This code contains only the definition of sample_mean and sample_variance, but the compiler keeps telling me that the function call of sample_mean inside the definition of sample_variance (which is double average= sample_mean(v);) is ambiguous. What is wrong with my program?

Vokram
  • 2,097
  • 4
  • 19
  • 27

3 Answers3

3

Your definitions have different signatures than the declarations.

Simple cure: move the definitions above main, and forget about forward-declaring the functions.

Forward-declaring the functions is a C-ism, not a particularly bright idea in C++. It just adds work, and creates problems. As you discovered.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • It could even work without moving the functions above `main`, as the compiler used by Xcode [got smarter about this recently](http://stackoverflow.com/questions/9884533). – zoul Aug 13 '12 at 07:20
  • 6
    @zoul: well, standard C++ is standard C++. standard C++ requires a declaration (which can be a definition) before use. language extensions are language extensions, and other languages are other languages. – Cheers and hth. - Alf Aug 13 '12 at 07:24
  • Given that he’s using Xcode, we could be talking Objective-C++. I don’t know the relation between standard C++ and Objective-C++, but maybe the feature I was talking about only works for Objective-C methods anyway. – zoul Aug 13 '12 at 09:42
1

You have 2 methods called sample_mean, not just one, and both can be called:

double sample_mean (const std::vector<double>& v)

and

double sample_mean (std::vector<double> v)
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

First you have a function declaration double sample_mean (std::vector<double>) and then you have a function definition double sample_mean (const std::vector<double>&). These are treated as identifiers of two different functions.

Paul Manta
  • 30,618
  • 31
  • 128
  • 208