3.1格式
(1) 公有成员是类与外部接口。
(2)私有成员只能在类中使用(其他方法暂时不讲)。
(3)与私有成员类似,差别在继承与派生时对派生类德影响不同。
(4)类中成员之间互相使用成员名互相访问。
3.2成员函数
3.2.1格式
成员函数有两种实现方法:
(1)类体内:
class Box
{
public:
double length; // 长度
double breadth; // 宽度
double height; // 高度
double getVolume()
{
return length * breadth * height;
}
};
(2)类体外:
class Box
{
public:
double length; // 长度
double breadth; // 宽度
double height; // 高度
// 成员函数声明
double getVolume();
};
//作用域限定名Box.
double Box::getVolume()
{
return length * breadth * height;
}
3.2.2成员函数之构造函数(类似python __init__
)
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行,构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。构造函数可用于为某些成员变量设置初始值。
(1)不含参数的构造函数:·也可以不写这种构造函数,编译器自动隐含构造函数,创建对象时候不用写参数,传参数通过其它成员函数。
using namespace std;
class Line
{
public:
void setLine(double len);
double getLine();
Line();//这是构造函数
private:
double length;//类内部变量
};
//构造函数定义,没有返回值,名字与类的名字相同。
Line::Line()
{
cout << "Object has been created." << endl;
}
//成员函数setLine()
void Line::setLine(double len)
{
length = len;
}
//成员函数getLine()
double Line::getLine()
{
return length;
}
int main()
{
Line Line1;
Line1.setLine(10);
cout << "The length of Line1 is: " << Line1.getLine() << endl;
}
(2)含参数的构造函数:传参数通过构造函数。
class Line
{
public:
Line(double len);
double getLength();
private:
double length;
};
//构造函数
Line::Line(double len)
{
cout << "Object has been created." << endl;
length = len;
}
//可以使用初始化列表,构造函数等价于
//Line::Line(double len):
// length(len)
//{
// cout << "Object has been created." << endl;
//}
double Line::getLength()
{
return length;
}
int main()
{
Line Line1(10);
cout << "The length of Line is: " << Line1.getLength() << endl;
}
3.2.3成员函数之析构函数