有没有办法在当前类中打印复合数据类型的所有属性

时间:2016-06-28 21:54:29

标签: c++ class templates

这里我在模板中有一个堆栈类;

template <class T, int s>
class stack
{
private:
  int size;  //size of stack
  T array[s]; // use array to implement stack, s is an initial argument
}

和班级类型Book;

class Book
{
public:
  string title;
  int year;
}

我可以在main中声明stack<Book, 10> bs; 有没有办法使用"title, year"中的函数打印所有stack?请记住,这是一个模板,它应该是其他一些类的通用,如

class movie  
{
public:
  string title;
  int year;
}

提前谢谢。

2 个答案:

答案 0 :(得分:2)

您应该公开T对{1}}的访问权限。迭代器,并为print()类提供movie函数。

将容器紧密地连接到其所包含的物品通常是一个坏主意。

通过标准容器,我会使用类似这样的东西

 template <typename Container>
 std::ostream& operator<<(std::ostream& os, Container c) {
    for(auto x : c) {
       os << x << std::endl;
    }
    return os;
 }

以及类Book的覆盖:

 std::ostream& operator<<(std::ostream& os, const Book& book) {
      os << book.title << " " << book.year;
      return os;
 }

答案 1 :(得分:2)

当然,templating提供编译时多态性,这意味着您假定的printAll函数将适用于定义正确函数的任何类型,即您可以这样做:

void printAll() {
    for (auto it = array.begin(); it != array.end(); ++array)
        cout << it->title << ", " << it->year << "\n";
}

但是这会将你的类成员紧密地耦合到堆栈类。您可以通过提供常规打印功能使其更加抽象:

Book::print() {
    cout << "The book " << title << " is from " <<  year << "\n"
}

然后在堆栈中使用此函数:

void printAll() {
    for (auto it = array.begin(); it != array.end(); ++array)
       it->print();
}

现在可以使用任何支持打印功能的类型。从这里你可以不断提高,例如。您可以重载流操作符来执行此操作:

cout << (*it);