如何在C ++中通过公共函数访问私有函数成员?

时间:2018-08-11 07:53:54

标签: c++ class private-members

此程序用于对 矩形 area()perimeter()进行简单计算。它正在编译并且运行良好,但是答案是错误的(计算)。我想我通过使用公共方法调用私有成员函数弄乱了他们。谁能指出我的错误?

// recClass.h

#ifndef RECTANGLE_H
#define RECTANGLE_H

class Rectangle{
    public:
        Ractangle(double length = 1.0,double width = 1.0);
        void setLengthAndWidth(double,double);
        double getLength();
        double getWidth();
        void printAreaAndPerim();
    private:
        double length;
        double width;
        double perimeter();
        double area();

};

#endif  

// Rectangle.cpp

#include<iostream>
using std::endl;
using std::cin;
using std::cout;

#include "recClass.h"

void Rectangle::setLengthAndWidth(double a,double b){
    length = a;
    width = b;
}
double Rectangle::getLength(){
    return length;
}
double Rectangle::getWidth(){
    return width;
}

double Rectangle::perimeter()
{
    double perim;
    perim = (length + width) * 2;
    return perim;
}

double Rectangle::area()
{
    double areaOfRec;
    areaOfRec = length * areaOfRec;
    return areaOfRec;
}

void Rectangle::printAreaAndPerim(){
    cout << "Has the Perimeter: " << perimeter() << "\nAnd area: " << area() << endl;
}  

// RectangleMain.cpp

#include<iostream>
using std::endl;
using std::cin;
using std::cout;

#include "recClass.h"

int main()
{
    Rectangle rec;
    rec.setLengthAndWidth(4.2,5.5);

    cout << "Rectangle with length: " << rec.getLength() <<"\nand width: " << rec.getWidth() << endl;
    rec.printAreaAndPerim();

        return 0;
}

1 个答案:

答案 0 :(得分:2)

我在代码中看到2错误。

  1. 在头文件中。 构造函数名称有错字。 “ Ractangle()”。

  2. Rechtangle.cpp 的区域功能中,变量areaOfRec未初始化。它用于计算。该功能应为:

    面积=长*宽