C++ Visual Studio “Non-standard syntax; use '&

2019-01-09 17:15发布

问题:

I have a ran in to this error (error C3867: non-standard syntax; use '&' to create a pointer to member) a couple of times. I know this question has been asked a lot of times, but I don't get why the problem happens and what I can do to fix it. I've read a lot of guides how pointers work and I've tried to play with the new knowledge, but I don't know how to do it correctly.

For this question I have made a simple code. Can someone help me understand why this error occurs and how to fix this code?

Error: error C3867: 'BankAccount::amountOfMoney': non-standard syntax; use '&' to create a pointer to member

Source.cpp

#include <iostream>
#include <string>

#include "BankAccount.h"

using namespace std;

int main(){

    BankAccount bankAccount1("testName", 200.0);

    cout << bankAccount1.amountOfMoney << endl;

}

BankAccount.h

#pragma once
#include <string>

using namespace std;

class BankAccount
{
public:
    BankAccount();
    BankAccount(string name, double money);
    ~BankAccount();
    double amountOfMoney();

private:
    string name;
    double money;
};

BankAccount.cpp

#include "BankAccount.h"


BankAccount::BankAccount()
{
}

BankAccount::BankAccount(string n, double m) {
    name = n;
}

BankAccount::~BankAccount()
{
}

double BankAccount::amountOfMoney() {
    return money;
}

回答1:

You forgot the function call operator (). Change your main code to:

int main(){

    BankAccount bankAccount1("testName", 200.0);

    cout << bankAccount1.amountOfMoney() << endl;

}

Without the parentheses it tries to print the address of a member function, which it is not able to do unless the function is not a member of a class.



回答2:

If you want to call your member function, use brackets.:

cout << bankAccount1.amountOfMoney() << endl;