//我想在这里使用3个函数,其中一个函数负责输入,一个函数用于计算,另一个函数用于输出,但我不知道如何引用//函数rec2和rec3中的变量。我想不使用指针来做
struct rectangle {
float length;
float width;
float area,perimeter;
};
rectangle rec1();
rectangle rec2();
rectangle rec3();
int main(){
rectangle f;
f = rec1();
f=rec2();
f = rec3();
return 0;
}
rectangle rec1(){
rectangle h;
cout<<"insert the length: ";
cin>>h.length;
cout<<"\ninsert width: ";
cin>>h.width;
return h;
}
rectangle rec2(){
rectangle z;
z.area=z.length*z.width;
z.perimeter=2*(z.length+z.width);
return z;
}
rectangle rec3(){
rectangle x;
cout<<"\narea is: "<<x.area<<endl<<"perimeter is: "<<x.perimeter<<endl;
return x;
}发布于 2014-01-28 23:01:57
您需要将方法添加到rectangle结构中。
struct rectangle
{
float length, width, area, perimeter;
void Input()
{
cout << "insert the length: ";
cin >> length;
cout << "\ninsert width: ";
cin>> width;
}
void Process(); // etc
void Output(); // etc
};
// Create a rectangle object and call it's methods
int main()
{
rectangle r;
r.Input();
r.Process();
r.Output()
}这些方法现在可以引用结构的成员变量。
发布于 2014-01-28 23:01:41
我建议你改变你的设计。
将输入、处理和输出函数作为方法放在rectangle结构中。
将函数放置在结构中允许它们访问数据成员。
发布于 2014-01-28 23:06:58
每次返回一个新的rectangle并将其赋值给您的f变量时,您都要覆盖f的所有成员,而不仅仅是在函数中修改的成员。您需要更改函数以直接修改f。不必为此使用指针,您可以使用引用:
struct rectangle {
float length;
float width;
float area, perimeter;
};
void rec1(rectangle&);
void rec2(rectangle&);
void rec3(rectangle&);
int main(){
rectangle f;
rec1(f);
rec2(f);
rec3(f);
return 0;
}
void rec1(rectangle &r){
cout << "insert the length: ";
cin >> r.length;
cout << endl << "insert width: ";
cin >> r.width;
}
void rec2(rectangle &r){
r.area = r.length * r.width;
r.perimeter = 2 * (r.length + r.width);
}
void rec3(rectangle &r){
cout << endl << "area is: " << r.area << endl << "perimeter is: " << r.perimeter << endl;
}但是,这毕竟是我们所说的C++。成员方法是您的朋友:)
struct rectangle {
float length;
float width;
float area, perimeter;
void rec1();
void rec2();
void rec3();
};
void rectangle::rec1(){
cout << "insert the length: ";
cin >> length;
cout << endl << "insert width: ";
cin >> width;
}
void rectangle::rec2(){
area = length * width;
perimeter = 2 * (length + width);
}
void rectangle::rec3(){
cout << endl << "area is: " << area << endl << "perimeter is: " << perimeter << endl;
}
int main(){
rectangle f;
f.rec1();
f.rec2();
f.rec3();
return 0;
}https://stackoverflow.com/questions/21418731
复制相似问题