问题
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