C++中使用指针输出值报错:std::string*转换错误原因咨询
C++指针编译错误原因解析
问题详情
编写了一段尝试用指针输出值的C++代码:
#include <iostream> #include <string> using namespace std; int main() { string food = "Pie"; string ptr = &food; cout << food << "\n"; cout << &food << "\n"; cout << ptr << "\n"; return 0; }
预期输出:
Pizza
0x开头的内存地址
0x开头的内存地址
编译时触发错误:
error: conversion from ‘std::string*’
错误原因
核心问题是指针类型声明不匹配:
&food是std::string*类型(指向string对象的指针),但你将其赋值给了std::string类型的变量ptr。C++不允许这种不同类型的隐式转换,因此编译器抛出类型转换错误。- 若要存储
&food这个地址,必须将ptr的类型声明为string*(string指针类型),而非普通的string对象类型。
修正代码
#include <iostream> #include <string> using namespace std; int main() { string food = "Pizza"; // 修正为预期的字符串值 string* ptr = &food; // 声明为string指针类型 cout << food << "\n"; cout << &food << "\n"; cout << ptr << "\n"; return 0; }
内容的提问来源于stack exchange,提问作者Sarah
相关产品推荐
相关产品推荐

