C++ Visual Studio 2015“非标准语法;使用‘&’创建指向成员的指针”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32062632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Visual Studio 2015 "non-standard syntax; use '&' to create a pointer to member"
提问by Lawrence Aiello
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:
我正在尝试用 C++ 实现我自己的链表,但终生无法弄清楚为什么会出现此错误。我知道有一个 STL 实现,但出于某些原因,我正在尝试自己的实现。这是代码:
#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?
在指定的行上,我收到错误“非标准语法;使用 '&' 创建指向成员的指针”。这到底是什么意思?
回答by songyuanyao
You're trying to return the member function value
, not the member variable data
. Change
您正在尝试返回成员函数value
,而不是成员变量data
。改变
const T& value() const { return value; }
to
到
const T& value() const { return data; }
回答by Raedwald
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.
您有一个返回 a 的方法const T&
,其中T
是模板参数。您打算返回对类型对象的常量引用T
。但是由于拼写错误,编译器认为您正在尝试将其与方法 ( value
)匹配,而不是类型T
( data
)的对象。编译器认为您正试图将其&
用作成员指针运算符,而不是对象引用运算符。但它足够聪明,有些事情不太对劲,因此发出警告。