cout <<string对象 编译出错引发的思考

#include <iostream>
using namespace std;
int main()
{
  string str="abcd";
  cout <<str <<endl; //error C2679: 二进制“<<”: 没有找到接受“std::string”类型的右操作数的运算符(或没有可接受的转换)      
  return 0;
}
复制代码
当你写下这样的代码时你将会得到一大堆的编译错误, 其中比较有用的在
      第一行:  error C2679: binary '<<' : no operator found which takes a right-hand operand of type     'std::string'.   
      第二行: 没有与这些操作数匹配的 "<<" 运 算符 操作数类型为:  std::ostream << std::string
 
      意思是说, 没有能够执行 operator<<(const std::string &) 的函数.  , 那么问题出在了哪里?
      记得 Thinking in C++  一书中说过, 将不是属于类的行为作为普通或者友员函数实现. 对于本例而言, 对 string 类的输出不是 string 的行为, 也不是 cout(ostream 的一个对象) 的行为, 因为 cout 不光输出 string 类型, 它还会输出别的很多类型. 因此, 对于 string 的输出, 不应该作为 cout 的一个成员. 所以 cout <<str <<endl; 
是无法通过编译的, 因为 iostream.h 中根本没有对 operator<<(string) 的重载.
根据 C++ Name lookup 约定, cout 函数会进行如下查找:

  • 查找 cout 的命名空间中, 使用点之前是否有 operator<<(std::ostream &, const std::string &) 的声明.
显然, iostream 中并没有相关的函数声明, 然而真正对于 operator<<(std::ostream &, const std::string &) 的声明在头文件 string 中. 将 cout 对 string 的重载放在 string 这个头文件中是正确的设计. 这也是本文阐述的主旨.
因此, 让上述代码工作, 仅需要加入#include< string> 头文件.

#include<string>是string容器的头文件
#include<cstring>是c++对c语言头文件#include<string.h>的改写。你明白了吗?
帮我改对#include<iostream> #include<fstream> #include<string> #include<vector> #include <algorithm> using namespace std; enum Grade { E=0,D,C,B,A }; class Student { public: int number; string name; double score; }; ostream& operator<<(ostream& out, Student& p) { return out; } bool compare(const Student& a, const Student& b) { return a.number < b.number; } void printVector(vector<Student>&students) { for (vector<Student>::iterator it = students.begin(); it != students.end(); it++) { cout << *it << " "; } cout << endl; } void test01() { vector<Student>students; printVector(students); } int main() { // 学生信息导入 ifstream infile; infile.open("student.txt",ios::in); if (!infile.is_open()) { cout << "文件打开失败" << endl; } vector<Student> students(27); char buf[] = { 0 }; while (infile>>buf) { cout << buf << endl; } infile.close(); // 成绩查询 int choice = 0; while (choice != 4) { cout << "请输入您要进行的操作:\n"; cout << "1. 按学号查询\n"; cout << "2. 按姓名查询\n"; cout << "3. 统计班级成绩\n"; cout << "4. 退出程序\n"; cin >> choice; if (choice == 1) { int number; cout << "请输入学号:\n"; cin >> number; auto it = find_if(students.begin(), students.end(), [number](const Student& s) { return s.number == number; }); if (it != students.end()) { cout << "学号\t姓名\t成绩\n"; cout << it->number << "\t" << it->name << "\t" << it->score << "\n"; } else { cout << "查无此人!\n"; } } else if (choice == 2) { string name; cout << "请输入姓名:\n"; cin >> name; auto it = find_if(students.begin(), students.end(), [name](const Student& s) { return s.name == name; }); if (it != students.end()) {
05-30
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值