gpt4 book ai didi

c++ - C++中如何通过公有函数访问私有(private)函数成员?

转载 作者:行者123 更新时间:2023-11-30 03:21:51 25 4
gpt4 key购买 nike

<分区>

此程序用于对矩形area()perimeter() 进行简单计算.它正在编译和运行正常,但答案是错误的(计算)。我想我通过使用公共(public)方法调用私有(private)成员函数搞砸了。谁能指出我的错误?

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;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com