如何在C++通过公共函数访问私有函数成员?
How to access private function member through public function in 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;
}
//矩形主.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的面积函数中,变量
areaOfRec
是未初始化的。它用于计算。该函数应为:面积 = 长 * 宽
相关文章:
- 使用不带参数的函数访问结构元素
- 删除目录函数访问被拒绝
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 我想要一个具有子函数的函数访问相同的命名函数,而不使用它取决于其子类的类
- 有没有办法通过 main 函数访问受保护的矢量大小而无需将其转换为公共?
- 如何在C++通过公共函数访问私有函数成员?
- 限制variadic模板类中的构造函数访问
- 从析构函数访问模板类构造函数的参数,可以吗?
- 变量 z 无法从其他函数访问变量 x
- 从静态成员函数访问私有非静态类变量 - C++
- 如何在 C++ 中从 void 返回函数访问变量
- 在类中使用映射并通过其他类的 get() 和 set() 函数访问值
- 无法从另一个函数访问文件范围变量的内容
- 是否可以从 C++ 中的构造函数访问对象名称?
- 使用C 中的共享_ptr从公共静态成员函数访问私有构造函数
- 使用静态成员函数访问静态数据成员
- 为什么我们可以从 C++ 中的成员函数访问 non_member 函数
- 如何使用 c++ 中的函数访问全局变量?
- 如何从 C++ 中的主函数访问类中的私有构造函数?