繁体   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