c++ - 如何通过 C++ 中的公共函数访问私有函数成员?
问题描述
该程序用于对矩形进行简单的area()
计算。它正在编译并运行良好,但答案是错误的(计算)。我想我通过使用公共方法调用私有成员函数来搞砸它们。谁能指出我的错误?perimeter()
recClass.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle{
public:
Rectangle(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
矩形.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;
}
解决方案
我在代码中看到 2 个错误。
在头文件中。构造函数名称有错字。“Ractangle()”。
在Rechtangle.cpp的 area 函数中,变量
areaOfRec
未初始化。它用于计算。函数应该是:面积=长*宽
推荐阅读
- angular - Getting some error in while setting up Angular using cmd
- python - Django如何选择forms.Form
- rest - 如何为 PUT 和 POST 正确构建 REST 端点
- javascript - 添加工具提示而不更改 HTML
- google-maps - 居中所有标记和折线谷歌地图插件颤振适合屏幕
- angular - 如何解决 ERROR TypeError: xxx is not a function?
- java - 使用 spring 数据从 sql 数据库中读取数据失败
- flutter - 我们到底什么时候使用 async-await 呢?
- ruby - 如何把名字写成大写?
- javascript - 固定顶部但绝对底部的字母顺序