[英]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;
}
你需要一個;
根據struct Company
的定義
在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
當a
和b
在另一個源文件中(全局)初始化時,您必須在源文件中使用需要使用extern
關鍵字訪問它們的外部鏈接來重新聲明它們。
// main.cpp #include <iostream> #include "structs.h" extern Company a; extern Company b; /* ... */
考慮在使用a
和b
地方進行初始化:
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. }
在函數PrintInfo
,由於您不修改參數,因此應將Company
類作為對const的引用傳遞,以避免復制,即使用以下方法聲明函數:
void PrintInfo(const Company& company)
結構需要一個“;” 在末尾
struct Company{
double salary;
int workers;
int bosses;
};
除了其他答案外, main.cpp
的代碼對您的initialization.cpp
a
和b
一無所知。
您需要在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.