【发布时间】:2021-03-08 13:35:47
【问题描述】:
在尝试理解和使用类和方法的过程中,我一直在尝试创建一个具有私有值的类,该类使用一种方法来更改这些值。我创建了一个程序,它请求用户输入(长度和宽度)并从这些值创建一个“矩形”(它只是存储他们输入的值,就好像它是一个矩形一样。)出于某种原因,我使用的方法没有'不要改变类中的私有长度和宽度值。我使用 .h 文件创建类,使用 .cpp 创建获取输入的函数,main.cpp 用于调用该函数。为了简单起见,我删除了 .cpp 文件中代码的输入验证部分,因为它不会影响类值。你能帮我找出我的错误吗?
我的 .h 文件,其中包含类:
#pragma once
#include <iostream>
using namespace std;
class Rectangle
{
private:
double length;
double width;
public:
Rectangle()
{
length = 0;
width = 0;
}
Rectangle(double a)
{
length = a;
width = a;
}
Rectangle(double l, double w)
{
length = l;
width = w;
}
void SetLenWid(double l, double w)
{
if (l == w)
{
Rectangle (l);
cout << "You have created a square with sides equal to " << length << endl;
}
else
{
Rectangle (l, w);
cout << "You have created a rectangle of length = " << length << " and width = " << width << endl;
}
}
};
Rectangle.cpp 文件:
#include "Rectangle.h"
#include <iostream>
void getInput()
{
double l, w;
cout << "Enter the length: ";
cin >> l;
cout << "Enter the width ";
cin >> w;
Rectangle init;
init.SetLenWid(l, w);
}
最后,我的 main.cpp:
#include "Rectangle.h"
#include "Rectangle.cpp"
#include <iostream>
using namespace std;
int main()
{
getInput();
return 0;
}
很抱歉这个冗长的问题!
【问题讨论】:
-
你用过调试器吗?
-
你想对
SetLenWid中的Rectangle (l);和Rectangle (l, w);做什么? -
你需要的大概是
void SetLenWid(double l, double w) { length = l; width = w; }
标签: c++ class constructor