帮忙改一下一个C++小程序~有一个错~不知道在哪~谢谢啦~

2025-01-05 00:29:00
推荐回答(3个)
回答(1):

1.类的定义应该放在使用之前,即将类的定义移到main()函数之前
2.应该将所有的this.修改为this->
3.三个成员变量的初始化方式有误
4.还有其它的格式错误以及语法错误

修改如下:

//---------------------------------------------------------------------------
#include
#include //注意这里
using namespace std;
class rectangle1 {

private:
double Width;//注意这里
double Height;//注意这里
string color;//注意这里

public:
rectangle1():Width(1),Height(1),color("white"){}//注意这里

double rectangle1 ::getWidth()
{
return Width;
}
void setWidth(double Width)
{
this->Width = Width;

}
double rectangle1 ::getHeight()
{
return Height;
}
void rectangle1 ::setHeight(double Height)
{
this->Height = Height;
}
string rectangle1 ::getColor()
{
return color;
}
void rectangle1 ::setColor(string color)
{
this->color = color;
}
double rectangle1 :: findArea()
{
double area;
area = Height * Width;
return area;
}
double rectangle1 :: findPerimeter()
{
double perimeter; //注意这里
perimeter = (Height *2) + (Width *2);
return perimeter;
}

string rectangle1 :: toString() {
stringstream sst;//注意这里
sst<<"Height: "<< Height//注意这里
<< "\n" << "Width: "
<< Width << "\n"
<< "Color: " << color << "\n" << //注意这里
"Area: " << findArea()<< "\n" <<
"Perimeter: " << findPerimeter() << "\n";
return sst.str();//注意这里
}};

int main(){

rectangle1 rectanglea ;//注意这里,变量不要和类重名
rectanglea.setHeight(40);
rectanglea.setWidth(4);
rectanglea.setColor("red");

cout<< "Rectangle 1: " <
rectangle1 rectangle2;//注意这里
rectangle2.setHeight(35.9);
rectangle2.setWidth(3.5);
rectangle2.setColor("red");

cout<< "Rectangle 2: " < }

//---------------------------------------------------------------------------

回答(2):

class rectangle1 {

private:
double Width = 1;
double Height = 1;
string color = "white";
类成员声明的时候除了静态变量,其他不能进行初始化 ,同时类rectangle在使用前要声明,所以要放在main前面

回答(3):

SB,把错误提示贴上来。