C++中如何打印存储自定义类对象的vector元素?
问题原因及解决方案
两个报错的根本原因
- 直接执行
cout << customerVector[0];报错:C++标准库没有为自定义的Customer类默认实现<<输出运算符,编译器不知道该按什么格式输出类的成员信息 - 执行
cout << customerVector[0].getName;报错:getName是类的成员方法,不是成员变量,必须加括号()完成函数调用才能拿到返回的姓名值,正确写法是customerVector[0].getName()
两种可行的解决方法
方法1:直接调用getter方法输出各成员
如果只是临时打印调试,直接取出各个成员输出即可,示例代码:
// 假设Customer类还有int类型的age、string类型的phone成员,对应getter为getAge()、getPhone() cout << "姓名:" << customerVector[0].getName() << ",年龄:" << customerVector[0].getAge() << ",电话:" << customerVector[0].getPhone() << endl;
方法2:重载<<运算符实现自定义类的直接输出
如果需要频繁打印Customer对象,推荐在Customer类的外部重载<<运算符,之后就可以直接用cout输出对象了,示例代码:
#include <iostream> #include <string> using namespace std; class Customer { private: string name; int age; string phone; public: Customer(string n): name(n) {} string getName() const { return name; } int getAge() const { return age; } string getPhone() const { return phone; } // 声明友元,让重载的<<运算符可以访问类的私有成员 friend ostream& operator<<(ostream& os, const Customer& c); }; // 实现<<运算符重载 ostream& operator<<(ostream& os, const Customer& c) { os << "客户信息:姓名=" << c.name << ",年龄=" << c.age << ",电话=" << c.phone; return os; }
重载完成后就可以直接执行你最开始写的cout << customerVector[0];完成输出了。
内容的提问来源于stack exchange,提问作者Starcadian
相关产品推荐
相关产品推荐

