\n";
Tom.Meow();
return0;
}
8、const成员函数
关键字const可以用来声明不能修改的变量。
也可将关键字const用于类中的成员函数。
要将类方法声明为const,可在方法声明中将所有参数括起的括号和分号之间放置关键字const。
如:
voidsomeFunction()const;
由于它被声明为const,因此不会修改其所属类的任何数据成员。
如果将一个函数声明为const的,而该函数的是实现通过修改某个成员变量的值而修改了对象,编译器将视其为错误。
尽可能将方法声明为const的,是一种良好的编程习惯。
这样让编译器捕获错误,而不致于称为等到程序运行时才出现bug。
9、类声明和方法定义的位置
为类声明的每一个函数都必须有定义,这种定义被称为函数实现。
定义必须位于编译器能够找到的文件中。
也可以将声明放在实现文件中,但这不是一种好的编程习惯。
大多数程序员采用的约定是,将声明放在头文件中,该头文件的名称与实现文件相同,但扩展名为.h、.hp或.hpp。
例:
可以将Cat类的声明放在一个名为Cat.hpp的文件中,而将类方法的定义放在一个名为Cat.cpp的文件中。
然后在Cat.cpp的开头加入如下代码,将头文件同.cpp文件关联起来:
#include“Cat.hpp”
这段代码告诉编译器,将Cat.hpp读入文件中。
10、内联实现
就像可以请求编译器将常规函数内联一样,也可以将类方法内联,只需在返回类型前加上关键字inline。
例:
inlineintCat:
:
GetWeight()
{
returnitsWeight;
}
也可以将函数的定义放到类声明中,这样,函数将自动成为内联的。
如:
classCat
{
public:
intGetWeight(){returnitsWeight;}
voidSetWeight(intaWeight);
}
内联函数的函数体紧跟在类方法声明之后,圆括号后没有分号。
11、将他类用作成员数据的类
一种常见的创建复杂类的方法是,首先声明较简单的类,然后再将其包含到较复杂的类的声明中。
先创建一个头文件,声明一个完整的类。
//声明一个完整的类
//点、线、面积
#include
classPoint//声明一个类,储存点的坐标x,y
{
public:
voidSetX(intx){itsX=x;}
voidSetY(inty){itsY=y;}
intGetX()const{returnitsX;}
intGetY()const{returnitsY;}
private:
intitsX;
intitsY;
};
classRectangle
{
public:
Rectangle(inttop,intleft,intbottom,intright);
~Rectangle(){}
intGetTop()const{returnitsTop;}
intGetLeft()const{returnitsLeft;}
intGetBottom()const{returnitsBottom;}
intGetRight()const{returnitsRight;}
PointGetUpperLeft()const{returnitsUpperLeft;}
PointGetLowerLeft()const{returnitsLowerLeft;}
PointGetUpperRight()const{returnitsUpperRight;}
PointGetLowerRight()const{returnitsLowerRight;}
voidSetUpperLeft(PointLocation){itsUpperLeft=Location;}
voidSetLowerLeft(PointLocation){itsLowerLeft=Location;}
voidSetUpperRight(PointLocation){itsUpperRight=Location;}
voidSetLowerRight(PointLocation){itsLowerRight=Location;}
intGetArea()const;
private:
PointitsUpperLeft;
PointitsLowerLeft;
PointitsUpperRight;
PointitsLowerRight;
intitsTop;
intitsLeft;
intitsBottom;
intitsRight;
};
//包含类Rectangle
#include"Rectangle.h"
Rectangle:
:
Rectangle(inttop,intleft,intbottom,intright)
{
itsTop=top;
itsLeft=left;
itsBottom=bottom;
itsRight=right;
itsUpperLeft.SetX(left);
itsUpperLeft.SetY(top);
itsUpperRight.SetX(right);
itsUpperRight.SetY(top);
itsLowerLeft.SetX(left);
itsLowerLeft.SetY(bottom);
itsLowerRight.SetX(right);
itsLowerRight.SetY(bottom);
}
intRectangle:
:
GetArea()const
{
intWidth=itsRight-itsLeft;
intHeight=itsTop-itsBottom;
return(Width*Height);
}
intmain()
{
RectangleMyRectangle(100,20,50,80);
intArea=MyRectangle.GetArea();
std:
:
cout<<"面积为:
\t"<
std:
:
cout<<"左上角点的横坐标为:
";
std:
:
cout<std:
:
cout<<"\n";
return0;
}
12、结构
与关键字class极其相似的一个关键字struct,它用来声明结构。
在C++中,结构与类相同,只是其成员默认为公有的。
可以像声明类一样声明结构,并给它声明数据成员和函数。
—q83831295