C ++ cout如何打印字符* [英] c++ how does cout print a char*

查看:438
本文介绍了C ++ cout如何打印字符*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,函数getName()返回char *.我认为它应该(也可以)返回string.如果cout只是第一个字符的指针,如何将其正确打印到控制台?

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

推荐答案

cout,朋友们认为类型char *

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

如果要打印指针所指的单个字符,则必须取消引用首先,所以cout获得char类型.或者,由于C字符串是一个字符数组,因此可以使用其0 th 项.

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;

提供(在线检查):

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

这篇关于C ++ cout如何打印字符*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆