一、类和对象的定义
C++中对象的类型称为类(class),类是对象的抽象,而对象是类的具体实例。类是抽象的,不占用内存,而对象是具体的,占用存储空间。
类的声明格式:
class 类名{
public:
公用的数据和成员函数;
private:
私有的数据和成员函数;
protected:
受保护的数据和成员函数;
};
类中private(私有)和public(公用)、protected(受保护)称为成员访问限定符。
- 被private声明的为私有的成员,只能被本类中的成员函数引用,类外不能调用(通过类声明的对象实例也不能访问私有数据成员,但是对象实例可以通过类中的公用成员函数访问和修改私有数据成员),友元类除外;
- 被public声明的为公有的成员,既可被本类中的成员函数调用,也可以被类外的其他函数调用;
- 被protected声明的成员为受保护的成员,它不能被类外访问,但可以被派生类的成员函数访问。
二、类的成员函数
1、在类内定义成员函数:
class Student{
public:
void display(){//共用成员函数的定义
cout<<”num:”<<num<<endl;
cout<<”name:”<<name<<endl;
cout<<”sex:”<<sex<<endl;
}
private:
int num;
string name;
char sex;
};
2、在类外定义成员函数(一般推荐):
class Student{
public:
void display();//共用成员函数的声明
private:
int num;
string name;
char sex;
};
void Student::display(){
cout<<”num:”<<num<<endl;
cout<<”name:”<<name<<endl;
cout<<”sex:”<<sex<<endl;
}
::是作用域限定符,用于声明函数属于哪个类的,::还可用于避免多重继承的二义性。如果没有Student::的限定,display()指的是全局作用域中的display()函数。若在类中声明成员函数如下所示,则表示类的成员函数为内置函数。如果类中定义的成员函数不包括循环等控制结构,则C++默认它们为内置函数。如果在类外定义,则不默认为内置函数,必须加inline作显式声明。
inline void display();
inline void Student::display(){}//在类外定义display函数为内置函数
不同对象的数据成员是一般是不同的,因此每个对象所占用的存储空间只是该对象数据部分所占用的存储空间,不包括成员函数所占用的存储空间。成员函数是存储在对象空间之外的,不论它是在类内定义还是在类外定义,用inline都不能改变。
三、代码综合示例
示例代码如下(利用类找到数组中的最大值):
#include <iostream>
using namespace std;
//通过类找出数组中的最大值
class array_max{
public:
void set_value(); //声明成员函数
void max_value();
void show_value();
private:
int a[10];
int a_max;
};
void array_max::set_value(){
for(int i = 0; i < 10; i++)
cin >> a[i];
return ;
}
void array_max::max_value(){
a_max = a[0];
for(int i = 1; i < 10; i++)
if(a_max < a[i])
a_max = a[i];
return ;
}
void array_max::show_value(){
cout << a_max << endl;
return ;
}
int main()
{
array_max ptr;
//ptr.a_max = 1500; //a_max为私有成员,不能被对象访问,但是可以被共有成员函数set_value()修改
//cout << ptr.a_max;
ptr.set_value();
ptr.max_value();
ptr.show_value();
return 0;
}