C++派生函数的一个问题

来源:百度知道 编辑:UC知道 时间:2024/06/24 16:25:13
如下:
#include<iostream.h>
#include<math.h>
class Ploygons //定义基类
{
protected:
double area; //面积变量
double perimeter; //周长变量
public:
Ploygons() {};
~Ploygons() {};
void printArea() const; //此处用关键字const是用来干什么的?
void printPeri() const;
};
void Ploygons :: printArea() const
{
cout<<"多边形的面积为:"<<area<<endl;
return;
}
void Ploygons :: printPeri() const
{
cout<<"多边形的周长为:"<<perimeter<<endl;
return;
}
class Triangle : protected Ploygons //定义派生类
{
private:
double sideA;
double sideB;
double sideC;
void calcArea();
void halfPeri();
public:
Triangle(double sideAin,double sideBin,double sideCin); //构造函数
};
Triangle :: Triangle(double sideAin,double sideBin,double sideCin)
{
if((sideAin+sideBin<=sideCin)||(sideAin+sid

const 用法就是保证函数不修改参数
但是这是对函数本身的限定,外部调用是可以随意调用~~
你的代码主要问题是:
class Triangle : protected Ploygons //定义派生类
这里你声明成了保护继承,这样会导致基类里的公有变量成为子类里的保护变量,外部调用就会错了
只需改为
class Triangle : public Ploygons
就一切ok了

声明该函数为常成员函数。常成员函数可以访问常对象中的数据成员,但不能修改常对象中的数据。

看类的声明
void Ploygons :: printArea() const
这是一个类的常量成员函数,所以只能被常量的类实体调用,而且函数内部也只能调用其他的常量成员函数

所以想调用的话,就必须
const Triangle Tri(3,4,5);
Tri.printArea();