@ghostfn1
2016-04-18T00:02:18.000000Z
字数 1994
阅读 1627
C++
Update Time:160417 Sunday Night.
C++ classes
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).
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.
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.
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 将成员函数直接定义在类的内部。
class Date
{
public:
void setDate(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
int IsLeapYear()
{
return(year%4==0 && year%100!=0)||(year%400==0);
}
void Print()
{
cout<<year<<"."<<month"."<<day<<endl;
}
private:
int year, month, day;
}
2 在类声明中给出对成员函数的说明,而在类外面对成员函数进行定义(但成员函数仍然在类范围内)
class Date
{
public:
void setDate(int y, int m, int d);
int IsLeapYear();
void Print();
private:
int year, month, day;
};
void Date::SetDate(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
int Date::IsLeapYear()
{
return(year%4==0 && year%100!=0)||(year%400==0);
}
void Date::Print()
{
cout<<year<<"."<<month"."<<day<<endl;}
}
3 如果成员函数的声明和定义都在类体内,那么这个成员函数就是内联函数。如果要定义在类体外的成员函数作为内联函数处理,必须在成员函数的定义前加上关键字inline。
class Date
{
public:
void setDate(int y, int m, int d);
int IsLeapYear();
void Print();
private:
int year, month, day;
};
inline void Date::SetDate(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
inline int Date::IsLeapYear()
{
return(year%4==0 && year%100!=0)||(year%400==0);
}
inline void Date::Print()
{
cout<<year<<"."<<month"."<<day<<endl;}
}
4
成员函数重载:
int Add(int x);
int Add(int x, int y);
成员函数定义为内联函数:
int GetX(){return X;}
int GetY(){return Y;}