簡體   English   中英

在向量c ++中的對象中打印對象

[英]Print object within object in vector c++

我正在創建一個顯示銀行帳戶的項目。 我創建了一個Account類和Person類-Account擁有一個余額,一個帳號和一個Person對象,該對象具有名稱和地址。 我已經將三個Account對象存儲在一個矢量中,但無法弄清楚如何打印Person(即姓名和地址)。 以下是驅動程序內部的一些代碼片段:

#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();
}

我想念什么?

有兩種方法:

1)假設Person對象具有字段名稱和地址屬性(可能是std :: string),請執行以下操作:

cout << accountVec[index].getAccountHolder().name;
cout << accountVec[index].getAccountHolder().address;

如果屬性是私有的,請為Person類提供getname()和getaddress()操作,然后訪問它們。

cout << accountVec[index].getAccountHolder().getname();
cout << accountVec[index].getAccountHolder().getaddress();

2)如果您有自己定義的類(類型),請為它們定義運算符<<。

 ostream &operator<<( ostream &output, const Person &D )
      { 
         output << "Person.xxxx";
         return output;            
      }

C ++能夠使用流插入運算符<< ....輸出內置數據類型。但是,如果使用自定義定義類型,則ostream和定義的類(類型)是插入運算符涉及的兩種類型(操作數)。 ..因此簽名

ostream &operator<<( ostream &output, const Person &D )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM