类的设计,构造函数和析构函数 c/c++

如题所述

类是编程人员表达自定义数据类型的C++机制。它和C语言中的结构类似,C++类

支持数据抽象和面向对象的程序设计,从某种意义上说,也就是数据类型的设

计和实现。

一、类的设计
1.类的声明

class 类名
{
private: //私有
...
public: //公有
...
};

2.类的成员
一般在C++类中,所有定义的变量和函数都是类的成员。如果是变量,我们就叫

它数据成员如果是函数,我们就叫它成员函数。
3.类成员的可见性
private和public访问控制符决定了成员的可见性。由一个访问控制符设定的可

访问状态将一直持续到下一个访问控制符出现,或者类声明的结束。私有成员

仅能被同一个类中的成员函数访问,公有成员既可以被同一类中的成员函数访

问,也可以被其他已经实例化的类中函数访问。当然,这也有例外的情况,这

是以后要讨论的友元函数。
类中默认的数据类型是private,结构中的默认类型是public。一般情况下,变

量都作为私有成员出现,函数都作为公有成员出现。
类中还有一种访问控制符protected,叫保护成员,以后再说明。
4.初始化
在声明一个类的对象时,可以用圆括号()包含一个初始化表。

看下面一个例子:

#include iostream.h

class Box
{
private:
int height,width,depth; //3个私有数据成员
public:
Box(int,int,int);
~Box();
int volume(); //成员函数
};

Box::Box(int ht,int wd,int dp)
{
height=ht;
width=wd;
depth=dp;
}

Box::~Box()
{
//nothing
}

int Box::volume()
{
return height*width*depth;
}

int main()
{
Box thisbox(3,4,5); //声明一个类对象并初始化
cout< return 0;
}

当一个类中没有private成员和protected成员时,也没有虚函数,并且不是从

其他类中派生出来的,可以用{}来初始化。(以后再讲解)
5.内联函数
内联函数和普通函数的区别是:内联函数是在编译过程中展开的。通常内联函

数必须简短。定义类的内联函数有两种方法:一种和C语言一样,在定义函数时

使用关键字inline。如:

inline int Box::volume()
{
return height*width*depth;
}

还有一种方法就是直接在类声明的内部定义函数体,而不是仅仅给出一个函数

原型。我们把上面的函数简化一下:

#include iostream.h

class Box
{
private:
int height,width,depth;
public:
Box(int ht,int wd,int dp)
{
height=ht;
width=wd;
depth=dp;
}
~Box();
int volume()
{
return height*width*depth;
}
};

int main()
{
Box thisbox(3,4,5); //声明一个类对象并初始化
cout< return 0;
}

这样,两个函数都默认为内联函数了。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-16
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

using namespace std;
class student
{
public:
char *lpszBuff;
student();
~student();
};

student::student()
{
lpszBuff = (char *)malloc(sizeof(char)*128);
}
student::~student()
{
free(lpszBuff);
}
int main()
{
student a;

memcpy(a.lpszBuff, "Hello World!", 12);
printf("%s\n", a.lpszBuff);
return 0;
}
相似回答