Today, I am asked a similar question:
Template <typename T> class queue {public: Queue (INT _ age, string _ name); // const Queue (const queue & Q ); // copy constructor void print (); Private: int age; string name ;}; template <typename T> queue <t >:: Queue (INT _ age, STD :: string _ name): Age (_ age), name (_ name) {cout <"Run constructor" <Endl;} template <typename T> queue <t> :: queue (const queue & Q) {This-> age = Q. age; this-> name = Q. name;} template <typename T> void queue <t>: Print () {cout <"name:" <this-> name <", age: "<this-> age <Endl ;}
He asked:(1)Why isn't the copy constructor the following: Queue (const queue <t> & Q); why can we save the template type parameter t?(2)In the implementation of the copy constructor, why can I access the private member age and name of the variable q?
(1) If the first problem is not definedIn the queue (const queue <t> & Q) format, the compiler alsoExtended Queue (const queue & Q)In the queue (const queue <t> & Q) format, that is, the two effects are the same.
(2) I started to share my feelings with him about the second question. Why can I access the private member of the variable q.
In fact, the public, private, and protected we usually call are relative classes, not objects. And your class can access all members of your class (including private ones ). Q belongs to the queue <t> class, so it (copy constructor) can access all members of Q.
Class test {public: void print (const Test & T) {cout <t. Num <Endl;} PRIVATE: int num ;};
The above definition is correct.