如何将另一个类中的类的Array用作数组 [英] How use Array of a class in another classes as a array

查看:70
本文介绍了如何将另一个类中的类的Array用作数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#including Hello ''guys'';

// i have a dump question, my mind isn''t working now

HOW can i use these classes together(please_help_me A)?



----------------------------------------- -------------------------------------


------------------------------------------------------------------------------

class student
{
   public:
      student();
      ~student();
      int age;
      int ID;
      // want MAX 10 year for a student
      Year YEAR[10];     //<------ ERROR
};
student::student()
{
   //What should i do for declaring Array YEAR
}

class Year
{
   public:
      Year();
      ~Year();
      string name;
      int _year;
      //want MAX 7 book for a year
      book BOOK[];      //<------ ERROR
      //book BOOK[7]; ???
};
Year::Year()
{
   //Same Problem . .. !
}

class book
{
   public:
      book();
      ~book();
      int ID;
      string name;
};

推荐答案

一个解决方案是链表。其他解决方案是矢量。



使用矢量的一个例子:

One solution would be linked list. other solution would be vector.

an example of using vector:
#include <vector>
class a
{};

std::vector<a> a_arr;

a ob;
a_arr.push_back(ob);
</a>


为了简单起见,在C ++中,必须先定义一个类,然后才能在数组中使用它。 />


因此,在您的情况下,您必须首先定义 book 类,然后 Year class,最后是 student class。



正如在另一个解决方案中提到的,使用向量可能是一个更好的主意......但是在使用之前必须声明一个类这一事实无济于事。



在某些情况下,前进声明可以使用。这只是声明类型: class book; 。但是在你的特定情况下,它会有所帮助,因为你需要完整的定义来声明一个对象数组。



对于一个指针数组,它会有所不同但是它们不同其他问题,如记忆管理,超出了这个问题的范围。
To keep it simple, in C++, a class must be defined before it is used in an array.

Thus in your case, you would have to define book class first, then Year class and finally student class.

As mentionned in another solution, using a vector might be a better idea... but it will not help for the fact that a class must be declared before it is used.

In some situations, a forward declaration can be used. That is only declare the type as in: class book;. But in your specific case, it would help since you need the full definition to declare an array of object.

For an array of pointers, it would be different but they are other problems like memory managment that is beyond the scope of this question.


这篇关于如何将另一个类中的类的Array用作数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆