关于(const) char*的理解

409 阅读1分钟

char*的解读

std::cout

cout 本身是ostream对象,ostream类重载了<<操作符,如下:

因此实际输出到控制台的数据依赖于<<的右边的值的类型,编译器根据不同的类型选择不同的函数。
stackoverflow有一段说的特别好:

下面是一个例子:

int main()
{
	vector<const char*> vec;
	string s1("hello");
	string s2("world");
	vec.push_back(s1.c_str());
	vec.push_back(s2.c_str());
	for (auto itr = vec.begin(); itr != vec.end(); itr++) {
		cout << *itr << "\t";  // itr 为指向元素的指针,*itr即为对应的vector的元素
		cout << (void*)(*itr) << "\t";
		cout << *(*itr) << "\t";
		cout << "\n";
	}
	const char x = *(*(vec.begin()));
	cout << x << endl;

	char a[] = "hello";
	cout << *a << endl;
	cout << a << endl;
	return 0;
}

输出:

参考链接:
stackoverflow.com/questions/1…
en.cppreference.com/w/cpp/io/ba…
en.cppreference.com/w/cpp/io/ba…