簡體   English   中英

如何打印對象中的所有變量,以及如何打印一組選定的變量?

[英]How to print all variables in an object, and how to print a select set of variables?

class Person
{
public:
        string fname;
        string lname;
        string occupation;
        string gender;
        int age;
};
int main()
{
        Person bc;
        bc.fname = "Bevelry";
        bc.lname = "Crusher";
        bc.gender = "female";
        bc.occupation = "Doctor, USS 1701-D";
        bc.age = 40;
        cout << bc.all << "\n"; //Something like this?
}

我是否可以在不自己指定的情況下打印對象的每個變量? 我是否可以制作一個變量的選擇列表,比如變量數組,然后打印它們?

編輯:我不小心把 cout 放在了課堂上,現在修復了

這是不可能的。 在 C++ 中,沒有任何東西可以滿足您的需求。

一方面,人們可以很容易地說這在 C++ 中是不可能的。

然而,另一方面,人們可以補充說,當人們制作面向對象的計算機程序時,這種情況經常發生,而在 Java 中有用於此toString()方法 因此,您實際上可能會編寫自己的toString()方法(基於它在 Java 中的實現方式),並使用它。

祝你好運

我是否可以在不自己指定的情況下打印對象的每個變量?

不。

我是否可以制作一個變量的選擇列表,比如變量數組,然后打印它們?

不是自動的,但您可以創建std::any的集合並自己為它添加一些解碼。

例子:

#include <any>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

// decode and print one std::any
void decode_one(std::ostream& os, const std::any& a) {
    if(auto s = std::any_cast<std::reference_wrapper<std::string>>(&a)) os << s->get();
    else if(auto i = std::any_cast<std::reference_wrapper<int>>(&a)) os << *i;
    else if(auto d = std::any_cast<std::reference_wrapper<double>>(&a)) os << *d;
    // add more types to decode here
    else os << "<unknown type>";
}

// a custom ostream operator to decode a vector of anys:
std::ostream& operator<<(std::ostream& os, const std::vector<std::any>& va) {
    auto begin = va.begin();
    auto end = va.end();
    if(begin != end) {
        decode_one(os, *begin);
        for(std::advance(begin, 1); begin != end; std::advance(begin, 1)) {
            os << ',';
            decode_one(os, *begin);
        }
    }
    return os;
}

int main() {
    int a = 10;
    std::string b = "Hello world";
    double c = 3.14159;

    std::vector<std::any> va{
        std::ref(a),
        std::ref(b),
        std::ref(c)
    };
    
    c *= 2.;                 // just to show that the vector holds a reference

    std::cout << va << '\n'; // print the variables in the vector
}

輸出:

10,Hello world,6.28318

暫無
暫無

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

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