VS2017 “non-standard syntax; use '&' to cr

2019-09-21 20:18发布

问题:

class DefInt
{
private:
    double a;
    double b;
    double (*f)(double x);
    int N;
public:
    DefInt(double c, double d, double (*g)(double y))
    {
        a = c;
        b = d;
        f = g;
    }

    double BySimpson()
    {
        double sum = f(a) + 4 * f((a + b) / 2) + f(b);
        return sum * (b - a) / 3;
    }

};
double g(double y)
{
    double sum = 1 - y * y + y * y * y;
    return sum;
}
int main()
{
    int c = 1;
    int d = 2;
    double y;
    DefInt MyInt(c, d, g);
    cout << "BySimpson:" << MyInt.BySimpson << endl << endl;
    system("pause");
    return 0;
}

why is there a error saying 'DefInt::BySimpson': non-standard syntax; use '&' to create a pointer to member? By the way I ommited a similar DefInt member function,though it is nearly the same as Bysimpson, it works fine and no error occurs. I do not understand why. I have attched it here.

double ByTrapzold(int n)
{
    N = n;
    double sum = f(a + (b - a) / N);
    for (int i = 2; i <= N; i++)
    {
        sum = sum + 2 * f(a + (b - a) * i / N);
    }
    sum = sum + f(a + (b - a) * (N + 1) / N);
    return sum * (b - a) / (2 * N);
}

Thanks.

回答1:

On the line

cout << "BySimpson:" << MyInt.BySimpson << endl << endl;

You probably meant to make a call to BySimpson but your forgot the ()

cout << "BySimpson:" << MyInt.BySimpson() << endl << endl;

The reason you get this misleading error is because pre ISO standarization MyInt.BySimpson would actually mean you wanted the address just like for normal function the function name on its own gives the address of the function. Later however the use of & to take the address of a member was put in the standard as a requirement. So Visual Studio thinks you are still using the old syntax and wants you to use the new syntax.