为什么我的指针在 C++ 中输出字符串而不是内存地址?
我正在开发一个使用指针的字符串类,但我在理解我的 print
函数在这里如何工作时遇到了一些困难。具体来说,为什么cout << pString
输出字符串而不是它指向的动态数组的内存地址?我的理解是变量 pString 是一个指针。
class MyString
{
public:
MyString(const char *inString);
void print();
private:
char *pString;
};
MyString::MyString(const char *inString)
{
pString = new char[strlen(inString) + 1];
strcpy(pString, inString);
}
void MyString::print()
{
cout << pString;
}
int main( )
{
MyString stringy = MyString("hello");
stringy.print();
return 0;
}
I'm working on a string class that employs pointers and I'm just having some difficulty in understanding how my print
function works here. Specifically, why does cout << pString
output the string and not the memory address of the dynamic array that it's pointing to? My understanding was that the variable pString was a pointer.
class MyString
{
public:
MyString(const char *inString);
void print();
private:
char *pString;
};
MyString::MyString(const char *inString)
{
pString = new char[strlen(inString) + 1];
strcpy(pString, inString);
}
void MyString::print()
{
cout << pString;
}
int main( )
{
MyString stringy = MyString("hello");
stringy.print();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为
<<
运算符已被重载以处理char*
的情况并将其作为字符串打印出来。与地址相反(其他指针的情况也是如此)。我认为可以肯定地说,这样做是为了方便 - 以便轻松打印出字符串。
因此,如果你想打印出地址,你应该将指针转换为
void*
。This is because the
<<
operator has been overloaded to handle the case of achar*
and print it out as a string. As opposed to the address (which is the case with other pointers).I think it's safe to say that this is done for convenience - to make it easy to print out strings.
So if you want to print out the address, you should cast the pointer to a
void*
.变量
pString
是一个指针。但是,与输出流一起使用时<<
的实现知道,如果您尝试输出char *
,则输出应打印为 null-终止的字符串。尝试:
The variable
pString
is a pointer. However, the implementation of<<
when used with an output stream knows that if you try to output achar *
, then the output should be printed as a null-terminated string.Try:
这是因为“<<”会自动跟随指针并打印出字符串,而不仅仅是打印出内存地址。这在 printf 中更容易看到,因为您可以指定指针的打印输出或指针引用的内容。
你可以看到这里%s打印出字符串,%p打印出内存地址。
This is down to the fact that "<<" will automatically follow the pointer and print out the string instead of just printing out the memory address. This is easier to see in printf as you can specify the print out of a pointer OR what the pointer references.
You can see here that %s prints out the string and %p prints out the memory address.