A bit of confusion about C ++ Access Permissions

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.