我有这个功能:
void strPointerTest(const string* const pStr)
{
cout << pStr;
}
Run Code Online (Sandbox Code Playgroud)
如果我这样称呼它:
string animals[] = {"cat", "dog"};
strPointerTest(animals);
Run Code Online (Sandbox Code Playgroud)
它返回第一个元素的地址.所以我期待如果我取消引用它,我会得到数组的第一个元素但是这样做:
void strPointerTest(const string* const pStr)
{
cout << *(pStr);
}
Run Code Online (Sandbox Code Playgroud)
它甚至不会让我编译.我尝试使用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);
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么要downvote.我正在寻求帮助,因为它不会在我的头上编译.如果它适用于你的结果并不意味着它也适用于我的.我正在寻求帮助,因为我不知道发生了什么.
编译错误是:
No operator "<<" matches these operands - operand types are: std::ostream << const std::string
Run Code Online (Sandbox Code Playgroud)
在一些编译器<iostream>碰巧也包括<string>标题.在其他编译器上,特别是Microsoft编译器,它显然没有.字符串的I/O运算符在<string>标题中声明.
您有责任包含所有必需的标题,即使代码有时无论如何都能正常工作.
所以修复就是添加
#include <string>
Run Code Online (Sandbox Code Playgroud)
在文件的顶部.
| 归档时间: |
|
| 查看次数: |
305 次 |
| 最近记录: |