C++ 无法获取函数以访问结构的成员

C++ 无法获取函数以访问结构的成员,c++,struct,C++,Struct,我试图使用一个函数来计算一个答案,使用存储在结构中的变量。每当我编译代码时,我都会遇到与结构成员的每次使用有关的错误。这件事我哪里做错了 干杯 #include <iostream> using namespace std; struct rectangle { double length, width, area, perimeter; // measurements for rectangle }; int calculations() { rect.ar

我试图使用一个函数来计算一个答案,使用存储在结构中的变量。每当我编译代码时,我都会遇到与结构成员的每次使用有关的错误。这件事我哪里做错了

干杯

#include <iostream>

using namespace std;

struct rectangle 
{

    double length, width, area, perimeter; // measurements for rectangle

};

int calculations() 
{

rect.area = rect.width * rect.length;

rect.perimeter = rect.width + rect.width + rect.length + rect.length; 

}

 int main() 
{  

rectangle rect; // rect is a rectnagle structure 

cout << "Please enter the length of your rectangle: " << endl; 
cin >> rect.length;
cout << "Please enter the width of your rectnagle: " << endl; 
cin >> rect.width; 

calculations();

cout << "The area of your rectangle is: " << rect.area << endl; 

cout << "The perimieter of your rectnagle is: " << rect.perimeter << endl; 

cout << rect.length << endl;
cout << rect.width << endl; 
cout << rect.area << endl; 
cout << rect.perimeter << endl;  

}
添加一个参数:

void calculations(rectangle& rect) 
{

    rect.area = rect.width * rect.length;

    rect.perimeter = rect.width + rect.width + rect.length + rect.length; 

}
然后打电话:

calculations(rect);

您尚未声明rect:

int calculations() 
{

rect.area = rect.width * rect.length;

rect.perimeter = rect.width + rect.width + rect.length + rect.length; 

}
在您的示例移动中:

rectangle rect; // rect is a rectnagle structure 
要使其全球化:

};

rectangle rect; // rect is a rectnagle structure 
int calculations() 
{

尝试使用此选项,因为在计算函数的作用域中没有定义rect。函数的问题在于它使用的名称rect不是全局的,并且是在函数定义之后定义的。所以函数不知道什么是rect

将函数重新定义为

void calculations( rectangle &rect ) 
{
    rect.area = rect.width * rect.length;

    rect.perimeter = rect.width + rect.width + rect.length + rect.length; 
}
把它称为

calculations( rect );

在调用send the parameter as a argument calculations(rect)时,这会修复它,谢谢!可能是一个愚蠢的问题,你能告诉我参数括号内矩形后的符号和的意义吗?@MichaelDelahorne
&
将参数作为一个参数。如果没有它,将复制矩形对象,并且在计算函数中所做的修改不会影响主函数中的矩形对象。您还可以使用指针
*
实现相同的功能,或者根据需要返回一个新的矩形对象。
void calculations( rectangle &rect ) 
{
    rect.area = rect.width * rect.length;

    rect.perimeter = rect.width + rect.width + rect.length + rect.length; 
}
calculations( rect );