[英]Print object within object in vector c++
I'm creating a project where I'm displaying a bank account. 我正在创建一个显示银行帐户的项目。 I've created a class Account and class Person - Account holds a balance, an account number, and an object of Person, which has a name and address.
我创建了一个Account类和Person类-Account拥有一个余额,一个帐号和一个Person对象,该对象具有名称和地址。 I've stored three Account objects in a vector, but can't figure out how to print the Person (namely, the name and address).
我已经将三个Account对象存储在一个矢量中,但无法弄清楚如何打印Person(即姓名和地址)。 Here are some snippets of my code inside my driver:
以下是驱动程序内部的一些代码片段:
#include <iostream>
#include <string>
#include <vector>
#include "Account.h"
#include "Person.h"
using namespace std;
// Creates Person object Drew with name "Drew" address "60 N Main"
Person Drew("Drew", "60 N Main");
// Create Account DrewAccount with account number 1, using Person Drew,
// and setting balance to 500.00
Account DrewAccount(1, Drew, 500.00);
// This is inside my printAccount function
int size = accountVec.size();
for (unsigned int index = 0; index < size; index++)
{
cout << accountVec[index].getAccountNum();
// This accountHolder is the Person object Drew and is giving me issues
// Gives Error:no operator "<<" matches these operands
// operand types are: std::ostream << Person
cout << accountVec[index].getAccountHolder();
cout << accountVec[index].getAccountBal();
}
What am I missing? 我想念什么?
There are two ways of doing it: 有两种方法:
1)Assuming Person object has fields name and address attributes(std::string probably), do this: 1)假设Person对象具有字段名称和地址属性(可能是std :: string),请执行以下操作:
cout << accountVec[index].getAccountHolder().name;
cout << accountVec[index].getAccountHolder().address;
If the attributes are private, provide getname() and getaddress() operations to Person class and then, acess them. 如果属性是私有的,请为Person类提供getname()和getaddress()操作,然后访问它们。
cout << accountVec[index].getAccountHolder().getname();
cout << accountVec[index].getAccountHolder().getaddress();
2) If you have your own defined classes(types), define operator << for them. 2)如果您有自己定义的类(类型),请为它们定义运算符<<。
ostream &operator<<( ostream &output, const Person &D )
{
output << "Person.xxxx";
return output;
}
C++ is able to output the built-in data types using the stream insertion operator <<....But if you use custom defined types, ostream and your defined class(type) are the two types(operands) involved in insertion operator...hence the signature C ++能够使用流插入运算符<< ....输出内置数据类型。但是,如果使用自定义定义类型,则ostream和定义的类(类型)是插入运算符涉及的两种类型(操作数)。 ..因此签名
ostream &operator<<( ostream &output, const Person &D )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.