Why does my pointer output a string and not a memo

2020-02-12 13:11发布

问题:

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;
}

回答1:

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.

So if you want to print out the address, you should cast the pointer to a void*.



回答2:

The variable pString is a pointer. However, the implementation of << when used with an output stream knows that if you try to output a char *, then the output should be printed as a null-terminated string.

Try:

cout << static_cast<void *>(pString);


回答3:

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.

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char** argv)
{
    char string1[] = "lololololol";
    char* string2;

    string2 = string1;

    printf("%s",string2);
    printf("%p",string2);

    return EXIT_SUCCESS;
}

You can see here that %s prints out the string and %p prints out the memory address.