在Python中构建类似于__repr__的对象的可打印表示

Constructing printable representation of an object similar to __repr__ in Python

本文关键字:对象 打印 表示 repr 构建 类似于 Python      更新时间:2023-10-16

我对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);
}

我想给出BankshowAccounts方法函数,该函数向用户显示所有他们有权访问的帐户对象。我想制作此可打印,以便可以在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
}