2017-10-10 75 views
-6

概述:我正在尝试创建一个具有多个类的银行帐户程序(确切地说是4个)。这里的层次结构 -如何设置和调用多个类的私有数据成员?

银行

客户账户;

帐户

存款depositor_info;

Int Account_number;

Double account_balance;

存款

名称depositor_name;

string社会安全号码;

名称

字符串首,末;

我可以设置存款人的名字,然后分配给存款人的账户。不过,我似乎无法打印出储户的名字。以下是主要的测试代码:

Account test[MAX_ACCTS]; 

string first = "john", last = "doe", social = "132456789"; 
int acctNumber = 987654; 
Name name; 
Depositor depositor; 

name.setFirst(first); // works 
name.setLast(last); // works 

depositor.setName(name); // this works 
depositor.setSSN(social); // this works 

test[1].setDepositor(depositor); // this also works. 

cout << test[1].getDepositor(); // Here I get an error: 
no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Depositor') 

我在做什么错了?

+2

阅读关于[mcve]。和[ask] questions –

+1

顺便说一下,您是否阅读过错误信息?那句话中你不明白的是什么字? –

+1

你没有告诉C++如何打印一个'Depositor'。你的意思是使用'cout << test [1] .getDepositor()。depositor_name;'?或者,您可以添加一个可以打印“Depositor”的函数,例如[这里](https://stackoverflow.com/questions/19167404/operator-overloading-ostream-istream)所述。 – nwp

回答

2

您需要为std::ostream&Depositor const&定义一个自定义operator<<过载作为参数。 C++不会隐式知道如何将对象转换为文本。

std::ostream & operator<<(std::ostream & out, Depositor const& depositor) { 
    out << depositor.getName().getLast() << ", " << depositor.getName().getFirst(); 
    out << "; " << depositor.getSSN(); 
    return out; 
} 

显然,如果只是打印名称+ SSN不是所需的行为,您可以调整特定行为。