C++ 如何从外部访问结构?

C++ 如何从外部访问结构?,c++,data-structures,C++,Data Structures,Decision.h typedef struct DST { float salary; float x1; float x2; }; struct DST person; decision() { std::vector<std::vector<DST>> person(300); for(int i = 0; i < 300; i++) person[i].resize(300); //An

Decision.h

typedef struct DST
{
    float salary;
    float x1;
    float x2; 
};

struct DST person;

decision()
{  
    std::vector<std::vector<DST>> person(300);
    for(int i = 0; i < 300; i++) 
    person[i].resize(300); 
    //And made some computation to save the data in 2d structure person
}
//In this header I want to access person structure

extern DST person;

check()
{
    for(int i=0; i<300; i++)
    {
        for(int j=0; j<300;j++)
        {
            conf[0]+= person[j][i].salary;
        }
    }
}

请帮我解决这个问题。

我将尝试从您的代码中提取您真正想要做的事情,并为您提供一些关于如何做的指导

首先,如果您正在编写C++(而不是纯C),则可以将DST的TyPulf和显式语句作为结构。这是您的第一个代码,应该是:

struct DST {
   float salary;
   float x1;
   float x2; 
};
接下来,正如Praetorian在上面的评论中提到的,您需要让您的函数访问您的数据。这可以像您尝试的那样使用全局变量来完成,但这通常是一个坏主意

建议的做法是在函数或类中声明变量,并根据需要将其作为参数传递给其他函数

一个简单的例子:

// A function working on a DST
void printDST(DST &aDST) {
    cout << "Salary: " << aDST.salary 
         << "\nx1: " << aDST.x1 
         << "\nx2: " << aDST.c2 
         << endl;
}

int main() {
    DST person = { 10000.0f, 0.0f, 0.0f}; // Declare and initialize a DST object.

    //Pass this person to a function
    printDST(person);

    return 0;
}
要使用此功能,请执行以下操作:

int main() {
    // Create vector of DSTs
    std::vector<DST> employees(300);

    // Initialize them somehow....

    // Calculate combined salaries:
    double total_salaries = sum_DST_salaries(employees);

    // Print it:
    cout << "Total salaries are: " << total_salaries << endl;

    return 0;
}
intmain(){
//创建DST的向量
病媒员工(300人);
//以某种方式初始化它们。。。。
//计算合并工资:
双倍总工资=总工资(员工);
//打印它:

无法使您的
检查
结构DST的方法(或成员函数)(应成为
)阅读更多的C++编程语言。结构不需要成为一个类。唯一的区别是默认成员访问,你告诉编译器<代码>人>代码>是“代码> dSt/CODE >类型,那么为什么你希望能够使用<代码>操作符索引它?
。在函数中声明
向量
不会神奇地改变全局变量的类型,因为这两个变量恰好具有相同的名称。而且您不应该在头文件中定义变量。但最重要的是,您需要读一本好书。
double sum_DST_salaries( const std::vector<DST> & dstVec ) {
    double sum = 0.0;
    for (int i = 0; i < dstVec.size(); i++) { // Using .size() is preferable 
          sum += dstVec[i].salary;            // to hard coding the size as it updates
    }                                         // nicely if you decide to change the size
    return sum;
}                                
int main() {
    // Create vector of DSTs
    std::vector<DST> employees(300);

    // Initialize them somehow....

    // Calculate combined salaries:
    double total_salaries = sum_DST_salaries(employees);

    // Print it:
    cout << "Total salaries are: " << total_salaries << endl;

    return 0;
}