先來看一個栗子吧。
#include"iostream" std::string info_extend; void main() { //std::cout << "printsomething: " <<info_extend << std::endl;//ERROR!! std::cout << "printsomething: " << info_extend.c_str() << std::endl; }
注釋掉的部分會出現錯誤:
2 IntelliSense: 沒有與這些操作數匹配的 "<<" 運算符
操作數類型為: std::basic_ostream<char, std::char_traits<char>> << std::string c:\Users\Administrator\Documents\Visual Studio 2013\Projects\博客\智能指針的使用\智能指針的使用\main.cpp 17 36 智能指針的使用
因為我們沒有包含頭文件 #include “string”,所以 沒有重載運算符<<,從而導致了錯誤。
解決的方法有兩種:
1.用c_str()函數,下面詳細介紹。
2.包含頭文件"string"
下面我們進入正題,請出我們的今天的主角 c_str() 他是一個函數哦。。。不要忘記了括號。。