編譯報錯 error C2679: binary '<<': no operator defined which takes a right-hand operand of type 'class std::basic_string...',乍看像是 std::string 不支援 operator<<,實則是命名空間未正確引入。
// 原始碼片段
#include
#include
using namespace std; // 這行被註解或遺漏
void main() {
string str1 = "Eventually I stopped caring...";
string str2 = "but that was the '80s so nobody noticed.";
str1.append(str2, 25, 15);
cout << "str1 is " << str1 << endl; // 編譯失敗
}
方法一:加入 using namespace std;(適合教學/小程式)
#include
#include
using namespace std; // 取消註解或新增此行
int main() { // 標準簽名應為 int main()
string str1 = "Eventually I stopped caring...";
string str2 = "but that was the '80s so nobody noticed.";
str1.append(str2, 25, 15);
cout << "str1 is " << str1 << endl;
return 0;
}
方法二:显式限定 std::(工程專案推薦,避免命名污染)
#include
#include
int main() {
std::string str1 = "Eventually I stopped caring...";
std::string str2 = "but that was the '80s so nobody noticed.";
str1.append(str2, 25, 15);
std::cout << "str1 is " << str1 << std::endl;
return 0;
}
std::string 的 operator<< 定義在 <string> 中,但屬於 std 命名空間。void main() 非標準,請一律使用 int main() 並回傳 0。using namespace std;,改用具體 using std::cout; 或完整限定名。修正後程式可正常輸出:str1 is Eventually I stopped caring...so nobody noticed.