Pages

vendredi 20 août 2010

C++ Class和Struct 以及如何设计 Class


struct 定义的结构默认情况下是public型的,而class 的默认情况是private 型的.其他都可以同用.
例如:
struct A{
int a;
char b;
};//此时a b 都是公有成员变量.
class B{
int a;
char b;

} //a b 分别属于私有成员变量.



A class is a data structure that contains related data and functions  
and is a unit of object-oriented programming.
Objects are an instantiation of a class  
and share the same properties although their contents may differ. 
Classes may inherit properties from other classes 
and support the encapsulation of data structures through access specifiers. 
The following steps explain how to create a C++ class.

  1. 1
    Define the class using the class keyword. This will provide the class a name, an optional list of access specifiers and an optional list of object names.

  2. 2
    Declare members as either access specifiers, data or functions within the body of the class statement.
3Provide the access specifiers to indicate one of the 3 levels of access in C++. 
  • Private members are only accessible by members of that class and their associates. 
  • Members who are protected are accessible by members in that class, any derived classes and any associates of those classes.
  • When the object is visible public members are accessible. 
  • The default is private.

  1. 4
    Learn the syntax of the class statement: class class_name  { access_specifier_1:member1; access_specifier_2:member2; ... access_specifier_n:membern; } object_names;

  2. 5
    Look at the following example of the class statement: class CTest { int i, j; public: void set_values (int,int); int total (void); } test; Note that the integers i and j do not have an access specifier and are therefore private. The function set_values and the integer total are public.

Aucun commentaire:

Enregistrer un commentaire