You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:03:15