简体   繁体   中英

Variables and Structs in C++

I came across this question:

"There are two types of variable data – dependent and independent. Which type is recommended to be created inside a struct and why?"

My attempt at an answer:

So I created some structs

struct Node{
    int node;
    Node *ptr;
}

struct Book{
    int page;
    Book *nxtPg;
}

struct Fruit{
    string name;
    float weight;
}

I can see that the variables are dependent. Is it correct to say that dependent variables would be recommended because structs group similar data together. And to answer the why part, is it correct to say that independent variables would defeat the purpose of creating a struct?

I suspect the question is designed to get you thinking about the object oriented paradigm: high cohesion, loose coupling of which there is plenty of information for you to read through on the internet.

Objects encapsulating data where that does not depend on other data (ie the objects do not depend on other objects) should be separate and not coupled . Objects that encapsulating data with dependencies have high cohesion and it is better to group that data together rather than scatter the data about meaning the objects would be coupled to other objects.

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