Lawrence Aiello
Lawrence Aiello

Reputation: 4638

Visual Studio 2015 "non-standard syntax; use '&' to create a pointer to member"

I am attempting my own Linked List implementation in C++ and cannot for the life of me figure out why I am having this error. I know there is an STL implementation but for reasons I am trying my own. Here is the code:

#include <iostream>

template <class T>
class ListElement {
public:
    ListElement(const T &value) : next(NULL), data(value) {}
    ~ListElement() {}

    ListElement *getNext() { return next; }
    const T& value() const { return value; }
    void setNext(ListElement *elem) { next = elem; }
    void setValue(const T& value) { data = value; }

private:
    ListElement* next;
    T data;
};

int main()
{
    ListElement<int> *node = new ListElement<int>(5);
    node->setValue(6);
    std::cout << node->value(); // ERROR
    return 0;
}

On the specified line, I get the error "non-standard syntax; use '&' to create a pointer to member". What the hell does this mean?

Upvotes: 7

Views: 22296

Answers (2)

Raedwald
Raedwald

Reputation: 48682

The problem here is the confusing combination of templates, multiple meanings of an operator, and a typo.

You have a method returning a const T&, where T is a template parameter. You intend that to return a constant reference to an object of type T. But due to a typo, the compiler thinks you are trying to match that to a method (value), rather than an object of type T (data). The compiler thinks you are trying to use & as the pointer-to-member operator, not the reference-to-object operator. But it is smart enough that something is not quite right, and so gives a warning.

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172964

You're trying to return the member function value, not the member variable data. Change

const T& value() const { return value; }

to

const T& value() const { return data; }

Upvotes: 8

Related Questions