The object of the class in order to associate/include a T-type instance, if the member variable includes t*/T&, this design is called "Aggregation" (aggregation), and in T form, it is called "composition" (combination)
1 //Combination Composition2 classMan {3 Eye Eye ;4 Nose Nose;5 }6 7 //Polymerization Aggregation8 classMan {9dog*Dog;Tenhouse&House ; One}
This answer is good, Baidu know:? What is the difference between composition and aggregation?
How do you see "reference types as member variables of a class"?
Refer to the answer to this question on StackOverflow:? Reference member variables as Class members
In particular , one of Manlio's answers :
It ' s called Dependency injection via constructor injection: (Dependency injection via constructors)
Class gets the dependency as an argument to it A constructor and saves the reference to dependent class as a private Variable.
For const-correctness I ' d write:
using T = int;class A{public: A(const T &thing) : m_thing(thing) {} // ...private: const T & m_thing;};
But a problem with this class is, it accepts references to temporary objects:
T t;A a1{t}; // this is ok, but...A a2{T()}; // ... this is BAD. //临时的匿名对象 属于 rvalue
It ' s better to add (requires c++11 at least):
class A{public: A(const T &thing) : m_thing(thing) {} A(const T &&) = delete; // prevents rvalue binding // ...private: const T &m_thing;};
Anyway if you change the constructor:
class A{public: A(const T *thing) : m_thing(*thing) { assert(thing); } // ...private: const T &m_thing;};
It's pretty much guaranteed that you won ' t has a pointer to a temporary.
Also, since the constructor takes a pointer, it ' s clearer to users of that they need to pay attention to the A Lifetim E of the object they pass.
After using t& as a member variable:
The ① must be assigned to this t& T in each contructor.
The ② object can no longer be assigned (=) after it is generated because the reference cannot be assigned two times.
Ask a question here? should I prefer pointers or references in member data? Next, anon's answer:
As everyone seems to is handing out general rules, I'll offer you both:
-
Never, ever use references as class members. I have never do so in my own code (except to prove to myself that I am right in this rule) and cannot imagine a case WH Ere I would do so. The semantics is too confusing, and it ' s reallynot what references were designed for. (Reference & was originally designed to look good in the case of operator overloading)
-
Always, always, use references if passing parameters to functions, except for the basic types, or when the algorithm req Uires a copy.
These rules is simple, and has stood me in good stead. I leave making rules on using the smart pointers (but, "not auto_ptr") as class members to others.
That is:? t& forms are used only in parameter passing , as member variables are used in t* form (never use t&).
Managing objects like Java:t& form is only used in parameter passing