列出C++类的成员

bac*_*i32 1 c++ class object

假设我有一个课程如下

class Rectangle{
    public:
    int height;
    int width;

};
Run Code Online (Sandbox Code Playgroud)

如何在不手动说明cout<<a.height或类似内容的情况下打印出该类成员的列表.换句话说,在不知道不同班级的成员的情况下,有没有办法让我打印出新班级的成员?

mig*_*tin 7

看起来你想要为std :: ostream对象重载operator << .我假设你想要这样做:

Rectangle rect;
std::cout << rect;
Run Code Online (Sandbox Code Playgroud)

代替:

Rectangle rect;
std::cout << "Width: " << rect.width << '\n';
std::cout << "Height: " << rect.width;
Run Code Online (Sandbox Code Playgroud)

重载函数(记住重载运算符是重载函数,除了具有特定签名)必须具有以下签名:

std::ostream& operator<<(std::ostream&, const Type& type);
Run Code Online (Sandbox Code Playgroud)

其中std :: ostream是一个ostream对象(例如文件),在这种情况下它将是std :: cout,而Type是你希望重载它的类型,在你的情况下将是Rectangle.第二个参数是一个const引用,因为打印出来的东西通常不需要你修改对象,除非我弄错了第二个参数不一定是const对象,但建议使用它.

它必须返回一个std :: ostream才能使以下内容成为可能:

std::cout << "Hello " << " operator<< is returning me " << " cout so I " << " can continue to do this\n";
Run Code Online (Sandbox Code Playgroud)

这是你在你的情况下这样做的方式:

class Rectangle{
  public:
    int height;
    int width;
};

// the following usually goes in an implementation file (i.e. .cpp file), 
// with a prototype in a header file, as any other function
std::ostream& operator<<(std::ostream& output, const Rectangle& rect) 
{
    return output << "width: " << rect.width <<< "\nheight: " << rect.height;
}
Run Code Online (Sandbox Code Playgroud)

如果Rectangle类中有私有数据,则可能需要使重载函数成为友元函数.我通常这样做,即使我不访问私人数据,只是出于可读性目的,这取决于你真的.

class Rectangle{
  public:
    int height;
    int width;

    // friend function
    friend std::ostream& operator<<(std::ostream& output, const Rectangle& rect);
};


std::ostream& operator<<(std::ostream& output, const Rectangle& rect)
{
    return output << "width: " << rect.width <<< " height: " << rect.height;
}
Run Code Online (Sandbox Code Playgroud)