C Cout如何打印一个char*

c++ how does cout print a char*

本文关键字:一个 char 打印 Cout 何打印      更新时间:2023-10-16

在下面的代码中,函数 getName()返回 char *。我想(也可以(返回string。如果cout只是指向第一个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;
}

cout和朋友认为 char *是C弦。

如果您希望它打印由指针引用的单个字符,则必须先解释它,因此cout获取char类型。或者,由于c弦是一个炭的数组,您可以使用其0 th item。

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

给出(在线检查(:

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