2014-07-12 2 views
-2

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 

이 좀 도와주십시오.

+0

합니다

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

당신이 뭔가를 할 것이라고이 기능을 사용하려면 당신의'struct DST' (그것은'class'가되어야합니다)의 메소드 (또는 멤버 함수)를'check'하십시오. 훨씬 더 C++ 프로그래밍 언어 책을 읽으십시오. –

+0

구조체가 클래스가 될 필요가 없습니다. 유일한 차이점은 기본 멤버 액세스입니다 – DTSCode

+0

컴파일러'person'은'DST' 타입이므로 컴파일러는'operator []'를 사용하여 인덱스를 생성 할 수 있기를 기대합니다. 함수 내에서'vector'를 선언한다고해서 두 변수가 같은 이름을 가지기 때문에 전역 변수의 타입을 마술처럼 변형하지는 않습니다. 그리고 헤더 파일에 변수를 정의해서는 안됩니다. 그러나 무엇보다도, 당신이해야 할 일은 좋은 책을 읽는 것입니다. – Praetorian

답변

1

실제로 코드에서 코드를 추출하고 코드 작성 방법에 대한 몇 가지 지침을 제공하려고 노력할 것입니다.

첫째, C++ (평범하지 않은 오래된 C)을 작성하는 경우 DST의 typedef와 명시 적 구문을 구조체로 생략 할 수 있습니다. 첫 번째 코드는 다음과 같아야합니다.

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을 무시한다.)이다

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; 
} 
관련 문제