简体   繁体   中英

C++ Static vectors in classes

I am working on a restraunt order system as a project for my computer science class and I was wondering if it would be best practice to use a static vector within my Order class to contain all of my orders or should I have it in my main program? I'm still working everything out but basically which one of these is better or is there another way entirely I should explore:

class Order {
public:
static vector<Order> orders; //should this be private instead?
}

int main(){
vector<Order> orders; //should I just pass this to my methods?

}

Deciding if static lists of objects makes sense or not, and which class shall hold these objects probably depends on why and how one wants to use the object list. So without being a bit more specific concerning the use-case, clear answers like "do" or "don't" might be opinion based.

The following is not meant as an answer, because of the missing use-case. But let me just share some thoughts with you:

I'd suggest to express the meaning/the purpose of the list, eg by meaningfully naming the variable. This could be openOrders , allOrderObjects , sharedOrders .

Connected with the meaning, you should probably hide the implementation detail that you use a vector . Especially the fact that you even expose the vector to the public makes it hard to ensure the meaning throughout the program. For example, if the meaning is openOrders , who prevents somebody from adding a closed order to the list?

So I'd hide the vector (make it private or at least protected); Add "control"-functions that restrict the access, name these functions such that the purpose becomes obvious, and restrict access to the list in order to ensure the meaning properly.

Depending on the meaning, you could also rethink the data structure vector . Maybe a map is more appropriate, eg if orders have a unique real world identifier like an order number shared with your customers and if you want to make sure to not create objects with the same order number twice...

Let me stop here. Maybe you get more thoughts from the community.

But I think the main issue is: get the meaning / the purpose of the list clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM