C++的头文件和源文件组织

Header and Source File Organization for C++

本文关键字:文件组织 文件 C++      更新时间:2023-10-16

我知道这似乎是一个常见的问题。然而,我似乎遵循了头文件的所有标准实践和指南,除了include保护之外,我认为这不会妨碍编译。所描述的链接器错误仅在CustomerInformation.h包含在包含主方法的CPlusPlusTraining.cpp中时发生。

这是我用于C++文件组织信息的一个来源:http://www.umich.edu/~eecs381/讲义/CpHeaderFileGuidelines.pdf

这是我的头

class CustomerInformation {
public: CustomerInformation();
public: char InformationRequest();
};

#include "stdafx.h"
#include <iostream>
#include <string>
#include "CustomerInformation.h"
using namespace std;
char InformationRequest() {
      string name;
      string lastName;
      int age;
      cout << "Please input your first and last name then your age: n";
      cin >> name >> lastName >> age;
      cout << "Customer Information: " << name + " " << lastName + " " << age << "n";
      char correction;
      cout << "Is all of this information correct? If it is Enter 'Y' if not Enter 'N' n";
      cin >> correction;
      if (correction == 'N') {
        cout << "Please Enter your information again: n";
        InformationRequest();
      }
      return correction;
}`

我加入了CPlusPlusTraining.cpp

#include "stdafx.h"
#include <iostream>
#include <string>
#include "CustomerInformation.h"
using namespace std;

头文件和源文件都具有相同的名称。头文件以.h结尾,而源文件以.cpp结尾。然而,我在编译时遇到了许多链接器错误。这里有什么问题?我将把重复的代码包含保存到另一天。谢谢

我如何调用文件中的方法,其中包含Main

CustomerInformation CI = CustomerInformation::CustomerInformation();
//information request
CI.InformationRequest(); //Not type safe for input

错误详细信息:

生成已开始:项目:CPlusPlusTraining,配置:调试Win32------1> CPlusPlusTraining.cpp//带Main的文件1> CPlusPlusTraining.obj:错误LNK2019:未解析的外部符号"public:__thiscall CustomerInformation::CustomerInformation(void)"(??0CustomerInformation@@QAE@XZ)在函数_wmain中引用1> CPlusPlusTraining.obj:错误LNK2019:未解析的外部符号"public:char__thiscall CustomerInformation::InformationRequest(void)"(?InformationRequest@CustomerInformation@@QAEDXZ)1> C:\Users\Gordlo2\documents\visual studio 2013\Projects\CPlusPlusTraining\Debug\CPlusPlusTraining.exe:致命错误LNK1120:2个未解析的外部======生成:0成功,1失败,0最新,0跳过======

您在没有类声明的情况下声明了Customer类的成员函数,导致编译器不知道它是您原型化的函数。应该是:

 char CustomerInformation::InformationRequest() {
 //your function stuff
 }