在Python中构建类似于__repr__的对象的可打印表示
Constructing printable representation of an object similar to __repr__ in Python
我对C 的新手大多数是使用Python,并且正在寻找一种方法来轻松构造对象的可打印表示形式 - 与Python的 repl类似。这是我的代码中的一些片段(当然是一家银行(。
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;
}
构造的帐户对象。我想拥有一个本质上是帐户对象数组的银行对象。
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 中做同样的事情。谢谢!
进行此操作的惯用方法是将输出流的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;
}
这是您要寻找的吗?
void BankSystem::showAccounts(){
for (Account a: listOfAccounts){
a.showAccount();
}
}
void Account::showAccount(){
cout << //all your printing information you want using your account
//class variables
}
相关文章:
- 如何仅使用对象名称打印特定于对象的成员
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数
- 打印抽象对象 c++
- 为什么平均打印数组元素比打印单个对象慢C++?
- 打印指向的对象
- 如何在 c++ 中打印存档中的对象向量
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 将对象放入地图后打印对象
- 打印对象的映射,其中另一个对象作为键
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 如何在C++中打印对象向量的内容
- 打印出对象向量中的每个元素C++
- 对象数组打印空白字符串
- C++ - 打印派生类对象的矢量<base*> 元素
- C++ - 使用 std::list,如何打印对象的私有成员的链接列表?
- 未正确的校验和释放对象 - 打印时错误
- GDB:如何从子对象打印/调用父函数
- 从对象打印二维矢量时出错
- 从对象打印2D int向量