c++ how does cout print a char* [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-22 01:43:50

问题


In the code below, the function getName() returns a char *. I would of thought that it should (it also can) return a string. How does cout correctly print it to the console if it is just a pointer to the first char?

#include <iostream>
#include <string>

using namespace std;

class Base
{
protected:
    int m_value;

public:
    Base(int value)
        : m_value(value)
    {
    }

    const char* getName() { return "Base"; }
    //string getName() { return "Base"; }
    int getValue() { return m_value; }
};


int main()
{
    Base base(5);
    std::cout << "Base is a " << base.getName() << " and has value " << base.getValue() << '\n';


    return 0;
}

回答1:


cout and friends consider the type char * to be a C-string.

If you want it to print a single character referred by a pointer, you have to dereference it first, so cout gets the char type. Or, since a C-string is an array of chars, you can use its 0th item.

const char* myString = "Hello";
cout << "string:    " << myString << endl
     << "*string:   " << *myString << endl
     << "string[0]: " << myString[0] << endl;

gives (check it online):

string:    Hello
*string:   H
string[0]: H


来源:https://stackoverflow.com/questions/49647482/c-how-does-cout-print-a-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!