"error: request for member ‘size’ in ‘a’, which is of pointer type"但我不认为这是一个指针

"error: request for member ‘size’ in ‘a’, which is of pointer type" but I didn't think it was a pointer

本文关键字:不认为 一个 指针 type is for member request error size in      更新时间:2023-10-16

所以,我以为我想做一些简单的事情,但显然不是。。。

我写这个函数是为了以后可以扩展它,并在需要时通过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;
}

但出于某种原因,我得到了:

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();

当我尝试编译时。有人能帮我翻译一下那个错误并解释一下->是什么吗,谢谢。

您正在传递一个strings数组,并试图在该数组上调用size()。数组在传递给函数时退化为指针,这解释了您的错误。

->运算符或"箭头运算符"(我使用的名称)只是(*obj).func()的简写。如果您有一个指向类对象的指针,这将非常有用。示例:

string *s = &someotherstring;
s->size(); //instead of (*s).size(), saves keystrokes
相关文章: