使用struct时如何参考3个函数

how to reference 3 functions while using struct

本文关键字:参考 3个 函数 struct 何参考 使用      更新时间:2023-10-16

//我想在这里使用3个函数,其中1个构造一个函数执行输入 一个用于计算,另一个用于排名,但我不知道如何参考函数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;
}

您需要将方法添加到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()
}

这些方法现在可以引用结构的成员变量

我建议您更改设计。
将输入,过程和输出功能放置为rectangle结构中的方法。

将功能放置在结构内,使他们可以访问数据成员。

每次返回新的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;
}