为什么我不能取消引用并在C++中引用此字符串

Why can't I dereference and cout this string in C++

本文关键字:引用 C++ 字符串 不能 取消 为什么      更新时间:2023-10-16

我具有此功能:

void strPointerTest(const string* const pStr)
{
    cout << pStr;
}

如果我这样称呼:

string animals[] = {"cat", "dog"};
strPointerTest(animals);

它返回第一个元素的地址。所以我期望如果我放弃它,我会得到数组的第一个元素,但这样做:

void strPointerTest(const string* const pStr)
{
    cout << *(pStr);
}

它甚至不允许我编译。我尝试使用INT而不是字符串尝试此操作,并且可以使用。有什么特别的字符串吗?我如何在此功能中检索字符串数组的元素?

编辑:

这是一个完整的示例,它不会在我的末尾编译:

#include <iostream>
void strPointerTest(const std::string* const pStr);
void intPointerTest(const int* const pInt);
int main()
{
    std::string animals[] = { "cat", "dog" };
    strPointerTest(animals);
    int numbers[] = { 9, 4 };
    intPointerTest(numbers);
}
void strPointerTest(const std::string* const pStr)
{
    std::cout << *(pStr);
}
void intPointerTest(const int* const pInt)
{
    std::cout << *(pInt);
}

我不知道为什么要裁员。我要寻求帮助,因为它不会编译我的目的。如果它在您的末端起作用,并不意味着它也适用于我的。我要帮助,因为我不知道发生了什么。

汇编错误是:

No operator "<<" matches these operands - operand types are: std::ostream << const std::string

在某些编译器中,<iostream>恰好还包括<string>标头。在其他编译器(特别是Microsoft编译器)上,显然没有。<string>标题中声明了用于字符串的I/O操作员。

即使代码有时碰巧起作用,包括所有所需的标头是您的责任。

因此,修复程序就是添加

#include <string>

在文件的顶部。