如何从外部访问结构?

时间:2014-07-12 06:31:08

标签: 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); 
    //And made some computation to save the data in 2d structure person
}

check.h

//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;
        }
    }
}

但我收到以下错误:

error C2676: binary '[' : 'DST' does not define this operator or a conversion to a type acceptable to the predefined operator
error C2228: left of '.salary' must have class/struct/union

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

我会尝试从您的代码中提取您实际想要做的事情,并为您提供一些指导方针。

首先,如果你正在编写C ++(而不是普通的旧C),你可以省略DST的typedef和explicit语句作为结构。那是你的第一个代码应该是:

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;
}

在冒险进入更复杂的示例之前,您应该熟悉C ++的函数和核心元素。但是为了完整性,这里有一个功能,它总结了DST的单个矢量的工资(暂时忽略const。):

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;
}
相关问题