读书人

string *pstr = new string(quot;hello wo

发布时间: 2012-05-01 12:48:58 作者: rapoo

string *pstr = new string("hello world!");
#include <iostream>
#include <string>
using namespace std;
int main
{
string *pstr = new string("hello world!");
cout<<pstr[0]<<endl;//输出hello world! 为什么 没有看懂
cout<<pstr<<endl; 输出地址
cout<<*pstr<<endl;输出hello world!
}


cout<<到底是怎么重载的 ?

[解决办法]
pstr[0]是string.自然是全部输出啊.

如果是输出第一个元素,应该pstr[0][0].
一般来说,如果不是重载*的, 那么 *p可以转换为 p[0]
[解决办法]

C/C++ code
    int* a = new int(1);    cout << a[0] << endl;   // 会输出1,a[0]表示从地址a开始的第一个int
[解决办法]
cout<<pstr[0]<<endl;//输出hello world! 为什么 没有看懂

先求出 pstr[0]
pstr[0]
--> *(pstr+0)
--> *pstr
--> 类型为string
编译器发现有个 ostream& operator<<(ostream& cout, const string& s);
于是输出 "hello world"
[解决办法]
P[0]和*p是一样的
[解决办法]
C/C++ code
string *pstr = new string("hello world!");//相当于string pstr[] = new string("hello world!");new string("hello world!")返回一个string对象,对pstr[0]初始化。因此,pstr[0]=="hello world!" 而pstr[1] pstr[2] ……都是不存在的楼主可以试试这样string *pstr = {new string("1.hello world!"),new string("2.hello world!"),new string("3.hello world!")};此时pstr[0], pstr[1], pstr[2]对应三串字符串char对应字符 string 对应字符串char*对应字符串(字符数组)string*对应字符串数组 

读书人网 >C++

热点推荐