使用struct时如何参考3个函数
how to reference 3 functions while using struct
//我想在这里使用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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 处理多个异常集合的C++方法
- 什么时候在C++中返回常量引用是个好主意
- C++ 参考:这两个语句有什么区别?
- 我有几个关于参考变量的问题
- 我正在学习C++,我不能使用指针访问参考吗?(举个例子)
- 可以将模板字段参考模板参数作为第一个模板参数传递
- CPP中的单个参考代表两种或多个数据类型
- Cython:从参考获得时缺少两个前元素的 Numpy 数组
- 用于获取多个容器参考的variadic模板
- 传递数组的一种病理方式:参考第一个元素
- 尝试构建C DLIB示例无法与数百个未定义的参考错误链接
- 使用struct时如何参考3个函数
- shared_ptr-如何忽略第一个参考
- 关于指针和参考文献的两个简短问题
- 参考资料 - 为什么以下两个程序产生不同的输出