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?
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.
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)
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.
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.