c++ - "error: request for member ‘size’ 中的 ‘a’ 是指针类型 "but I didn' t 认为它是一个指针

标签 c++ arrays

所以,我以为我正在尝试做一些简单的事情,但显然不是......

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

关于c++ - "error: request for member ‘size’ 中的 ‘a’ 是指针类型 "but I didn' t 认为它是一个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921998/

相关文章:

c++ - 安全的 C++ std::string 到 TCHAR * 转换?

c++ - 无法理解 CUDA 内核启动的行为

c++ - 一次移动多个无符号字符以便它们从一个字符流向另一个字符的最快方法是什么?

javascript - 列出 chrome 注册的服务人员

c++ - 下面的OpenCV源码有没有错误? (没有#else 的#ifdef)

c++ - 在 QStringList 中搜索特定项目,然后搜索可能包含项目的其他项目

php - 在数组 : If two highest value exists, 中进行比较,然后比较另一个值

javascript - 在脚本中介器 esb wso2 中获取错误 'Cannot read property "长度“来自未定义”

python - 如何在不遇到 MemoryError 的情况下逐步将一个巨大的字节数组写入文件

javascript - 在 Angular JS 中显示数组