每当我询问面积或周长时,它都会返回一些荒谬的值。 我尝试修复了2天,但还是一样! 下面是输出的代码和类!
我希望输出为100,但显示为
252134578 <<<<此
主代码:
std::experimental::filesystem
rect_class.hpp
#include <iostream>
#include "rect_class.hpp"
using namespace std;
int main()
{
rectangle rect;
int width= 10, height = 10, choice, newwidth, newheight;
bool loop = false;
while(loop == false){
cout << endl << endl;
cout << " *** Menu *** " << endl;
cout << "(1) Draw Rectangle" << endl;
cout << "(2) Area" << endl;
cout << "(3) Perimeter" << endl;
cout << "(4) Resize" << endl;
cout << "(5) Quit" << endl;
cout << "Enter your choice :";
cin >> choice;
cout << endl;
switch(choice){
case 2 :cout << rect.getArea();
break;
case 3 : cout << rect.getPerimeter();
break;
case 4 : cout << "enter your height : ";
cin >> newheight;
cout << "enter your width : ";
cin >> newwidth;
rect.setHeight(newheight);
rect.setWidth(newwidth);
break;
case 5 : loop = true;
cout << "exiting...";
break;
default: cout << "bro type the menu nums !!";
break;
}
};
我正处于编程之旅的开始之年,对于任何愚蠢的错误,我们深表歉意! :-)
答案 0 :(得分:1)
您的rectangle
类成员未初始化。您可以为变量int width= 10, height = 10
设置值,但不要将其传递给rectangle
类构造函数。
更改此代码:
rectangle rect;
int width= 10, height = 10, choice, newwidth, newheight;
对此:
int choice=0, newwidth=0, newheight=0; //always initialize variables!
rectangle rect(10, 10); //create rectangle with 10, 10
现在,您需要向rectangle
类添加构造函数:
class rectangle {
public:
rectangle() = delete; //we don't need it anymore
rectangle(int width = 0, int height = 0) : itsHeight(height), itsWidth(width ) { }
//... rest of your code
此构造函数允许您使用给定参数创建rectangle
或仅使用默认参数(0,0)进行创建。