C++ “错误:请求'a'中的成员'size',它是指针类型”但我不认为它是一个指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22921998/
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
"error: request for member ‘size’ in ‘a’, which is of pointer type" but I didn't think it was a pointer
提问by Jamie Twells
So, I thought I was trying to do something simple, but apparently not...
所以,我以为我正在尝试做一些简单的事情,但显然不是......
I wrote this function so I could extend it later and have a quick way to give the user a menu when required by going menu(mystrings)
:
我写了这个函数,所以我可以稍后扩展它,并有一个快速的方法在需要时为用户提供一个菜单menu(mystrings)
:
int menu(string a[]) {
int choice(0);
cout << "Make a selection" << endl;
for(int i=0; i<a.size(); i++) {
cout << i << ") " << a[i] << endl;
}
cin >> choice;
cout << endl;
return choice;
}
But for some reason I get:
但出于某种原因,我得到:
main.cpp: In function ‘int menu(std::string*)':
main.cpp:38:12: error: request for member ‘size' in ‘a', which is of pointer type ‘std::string* {aka std::basic_string<char>*}' (maybe you meant to use ‘->' ?)
int n = a.size();
when I try compiling. Could anyone translate that error for me and explain what ->
is, thank you.
当我尝试编译时。任何人都可以为我翻译该错误并解释是什么->
,谢谢。
回答by yizzlez
You are passing an array of strings
and trying to call size()
on the array. Arrays degenerate to pointers when passed to a function, which explains your error.
您正在传递一个数组strings
并尝试调用size()
该数组。数组在传递给函数时退化为指针,这解释了您的错误。
The ->
operator, or "arrow operator" (name I use), is just shorthand for (*obj).func()
. This is useful if you have a pointer to a class object. Example:
该->
经营者,或“箭经营者”(名字我使用),只是简写(*obj).func()
。如果您有一个指向类对象的指针,这很有用。例子:
string *s = &someotherstring;
s->size(); //instead of (*s).size(), saves keystrokes