我对C ++很陌生,过去大部分时间都使用过Python,我正在寻找一种方法来轻松构建对象的可打印表示 - 与Python的 repr 类似。以下是我的代码中的一些片段(当然是银行)。
class Account {
private:
int pin;
string firstName;
string lastName;
char minit;
int acc_num;
float balance;
float limit;
public:
float getBalance(void);
string getName(void);
void setPin(int);
void makeDeposit(float);
void makeWithdrawal(float);
Account(float initialDeposit, string fname, string lname, char MI = ' ', float x = 0);
};
Account::Account(float initialDeposit, string fname, string lname, char MI, float x) {
cout << "Your account is being created" << endl;
firstName = fname;
lastName = lname;
minit = MI;
balance = initialDeposit;
limit = x;
pin = rand()%8999+1000;
}
构建帐户对象。我想要一个Bank对象,它本质上是一个帐户对象数组。
class BankSystem {
private:
vector<Account> listOfAccounts;
int Client_ID;
public:
BankSystem(int id);
void addAccount(Account acc);
Account getAccount(int j);
};
BankSystem::BankSystem(int id) {
Client_ID = id;
listOfAccounts.reserve(10);
}
我想提供Bank
类showAccounts
方法函数,该函数向用户显示他们有权访问的所有帐户对象。我想把它打印出来,以便我可以在cout
中显示它。在Python中,我只需使用__repr__
来“字符串化”帐户对象,例如
def __repr__(self):
return 'Account(x=%s, y=%s)' % (self.x, self.y)
想知道我将如何在C ++中做同样的事情。谢谢!
答案 0 :(得分:2)
解决此问题的惯用方法是使用您的类重载输出流的operator<<
函数,例如
#include <iostream>
using std::cout;
using std::endl;
class Something {
public:
// make the output function a friend so it can access its private
// data members
friend std::ostream& operator<<(std::ostream&, const Something&);
private:
int a{1};
int b{2};
};
std::ostream& operator<<(std::ostream& os, const Something& something) {
os << "Something(a=" << something.a << ", b=" << something.b << ")";
return os;
}
int main() {
auto something = Something{};
cout << something << endl;
}
答案 1 :(得分:0)
这是你在找什么?
void BankSystem::showAccounts(){
for (Account a: listOfAccounts){
a.showAccount();
}
}
void Account::showAccount(){
cout << //all your printing information you want using your account
//class variables
}