为什么我的指针在C ++中输出一个字符串而不是一个内存地址? [英] Why does my pointer output a string and not a memory address in C++?
问题描述
我正在研究使用指针的字符串类,但是在理解我的print
函数在这里如何工作时遇到了一些困难.具体来说,为什么cout << pString
输出字符串而不是它指向的动态数组的内存地址?我的理解是变量pString是一个指针.
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;
}
推荐答案
这是因为<<
运算符已被重载以处理char*
的大小写并将其打印为字符串.与地址相反(其他指针就是这种情况).
This is because the <<
operator has been overloaded to handle the case of a char*
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.
因此,如果要打印出地址,则应将指针投射到void*
.
So if you want to print out the address, you should cast the pointer to a void*
.
这篇关于为什么我的指针在C ++中输出一个字符串而不是一个内存地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!