[关闭]
@ghostfn1 2016-04-18T00:02:18.000000Z 字数 1994 阅读 1627

C++ classes Usages

C++


Update Time:160417 Sunday Night.

  1. C++ classes
  2. A class in C++ is a user defined type or data structure declared with keyword class that has data and functions as its members whose access is governed by the three access specifiers private, protected or public (by default access to members of a class is private).
  3. A class in C++ differs from a structure (declared with keyword struct) as by default, members are private in a class while they are public in a structure.
  4. The private members are not accessible outside the class; they can be accessed only through methods of the class. The public members form an interface to the class and are accessible outside the class.
  5. Instances of these data types are known as objects and can contain member variables, constants, member functions, and overloaded operators defined by the programmer.
类的成员包括数据成员和成员函数,分别描述类的属性和行为。
访问权限修饰符:public private protected
私有类型的成员只允许本类的成员函数访问。
保护类型介于public和private之间,在继承和派生时可以体现其特点。

类中的数据成员可以是任意类型,包括整型、浮点型、数组、指针等,也可以是对象。自身类的对象不可以作为自身类的成员存在,但自身类的指针可以。

在类体中不允许对所定义的数据成员进行初始化。p121

类的成员函数
类中所有的成员函数都必须在类体内进行说明,但成员函数的定义叶可以在类体外给出。p122

1 将成员函数直接定义在类的内部。
  1. class Date
  2. {
  3. public:
  4. void setDate(int y, int m, int d)
  5. {
  6. year = y;
  7. month = m;
  8. day = d;
  9. }
  10. int IsLeapYear()
  11. {
  12. return(year%4==0 && year%100!=0)||(year%400==0);
  13. }
  14. void Print()
  15. {
  16. cout<<year<<"."<<month"."<<day<<endl;
  17. }
  18. private:
  19. int year, month, day;
  20. }
2 在类声明中给出对成员函数的说明,而在类外面对成员函数进行定义(但成员函数仍然在类范围内)
  1. class Date
  2. {
  3. public:
  4. void setDate(int y, int m, int d);
  5. int IsLeapYear();
  6. void Print();
  7. private:
  8. int year, month, day;
  9. };
  10. void Date::SetDate(int y, int m, int d)
  11. {
  12. year = y;
  13. month = m;
  14. day = d;
  15. }
  16. int Date::IsLeapYear()
  17. {
  18. return(year%4==0 && year%100!=0)||(year%400==0);
  19. }
  20. void Date::Print()
  21. {
  22. cout<<year<<"."<<month"."<<day<<endl;}
  23. }
3 如果成员函数的声明和定义都在类体内,那么这个成员函数就是内联函数。如果要定义在类体外的成员函数作为内联函数处理,必须在成员函数的定义前加上关键字inline。
  1. class Date
  2. {
  3. public:
  4. void setDate(int y, int m, int d);
  5. int IsLeapYear();
  6. void Print();
  7. private:
  8. int year, month, day;
  9. };
  10. inline void Date::SetDate(int y, int m, int d)
  11. {
  12. year = y;
  13. month = m;
  14. day = d;
  15. }
  16. inline int Date::IsLeapYear()
  17. {
  18. return(year%4==0 && year%100!=0)||(year%400==0);
  19. }
  20. inline void Date::Print()
  21. {
  22. cout<<year<<"."<<month"."<<day<<endl;}
  23. }
4
成员函数重载:
int Add(int x);
int Add(int x, int y);
成员函数定义为内联函数:
int GetX(){return X;}
int GetY(){return Y;}
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注