簡體   English   中英

在C ++中將頭文件,初始化文件和主文件用於結構

[英]Using a header file, initialization file, and main file for structs in C++

我在執行用結構編寫的程序時遇到困難。 我的程序有一個頭文件,一個初始化文件和一個主文件。 當我編譯它時,編譯器抱怨了,后來我發現我將結構名稱聲明為Company但使用company對其進行了初始化,因此我將其更改為Company但是在執行此操作后,編譯器仍然抱怨。 我怎樣才能解決這個問題? 任何幫助將不勝感激。 以下是我的三個文件的代碼:

structs.h:

#ifndef STRUCTS_H
#define STRUCTS_H

struct Company{
  double salary;
  int workers;
  int bosses;
}

#endif

initialize.cpp:

Company a = {1200340.99, 30000, 3};
Company b = {500320.85, 5000, 2};

main.cpp:

#include <iostream>
#include "structs.h"

void PrintInfo(Company company){
  using namespace std;
  cout << "salary: " << Company.salary << endl;
  cout << "workers: " << Company.workers << endl;
  cout << "bosses: " << Company.bosses << endl;
}

int main(){
  PrintInfo(a);
  PrintInfo(b);
  return 0;
}
  1. 你需要一個; 根據struct Company的定義

  2. PrintInfo您需要引用對象 company (小寫c)而不是Company類(大寫C),例如

     cout << "salary: " << company.salary << endl; // lowercase c cout << "workers: " << company.workers << endl; // lowercase c cout << "bosses: " << company.bosses << endl; // lowercase c 
  3. ab在另一個源文件中(全局)初始化時,您必須在源文件中使用需要使用extern關鍵字訪問它們的外部鏈接來重新聲明它們。

     // main.cpp #include <iostream> #include "structs.h" extern Company a; extern Company b; /* ... */ 

    考慮在使用ab地方進行初始化:

     int main() { Company a = {1200340.99, 30000, 3}; // Init here. Company b = {500320.85, 5000, 2}; // Init here. PrintInfo(a); PrintInfo(b); // return 0; // Unnecessary in main function. } 
  4. 在函數PrintInfo ,由於您不修改參數,因此應將Company類作為對const的引用傳遞,以避免復制,即使用以下方法聲明函數:

     void PrintInfo(const Company& company) 

結構需要一個“;” 在末尾

struct Company{
  double salary;
  int workers;
  int bosses;
};

除了其他答案外, main.cpp的代碼對您的initialization.cpp ab一無所知。

您需要在structs.h添加一個extern聲明,或者將其移動到main.cpp

但是,您還應該考慮不要使它們成為全局變量,如下所示:

int main()
{
    Company a = {1200340.99, 30000, 3};
    Company b = {500320.85, 5000, 2};
    PrintInfo(a);
    PrintInfo(b);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM