如何在为类创建 .h 和 .cpp 文件后删除错误?C++

How do I remove errors after creating .h and .cpp files for a class? C++

本文关键字:文件 删除 错误 C++ cpp 创建      更新时间:2023-10-16

所以我正在学习使用类.h,并在程序中.cpp文件,该文件读取包含有关银行帐户信息的文件。 最初代码工作正常,但是在创建 .h 和 .cpp 类文件后,事情不再那么顺利了,因为我遇到了对我来说没有意义的奇怪错误。

这是我的主 cpp 文件:

#include "Bankaccount.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{   string fileName;
cout << "Enter the name of the data file: ";
cin>>fileName;
cout<<endl;
bankAccount object(fileName);
return 0;
}

这是我的银行账户.h 文件

#ifndef BANKACCOUNT_H
#define BANKACCOUNT_H
#include <iostream>
#include <fstream>
#include <string>
class bankAccount
{
public:
bankAccount(string n);
bankAccount();
private:
ifstream sourceFile;
}

最后这是银行账户.cpp文件

#include "Bankaccount.h"
#include <iostream>
#include <fstream>
#include <string>
bankAccount::bankAccount(string n)
{
sourceFile.open(n.c_str());
}

现在正在生成这些错误:

includeBankaccount.h|13|error: expected ')' before 'n'|
includeBankaccount.h|18|error: 'ifstream' does not name a type|
includeBankaccount.h|14|note: bankAccount::bankAccount()|
includeBankaccount.h|14|note: candidate expects 0 arguments, 1 provided|
includeBankaccount.h|4|note: bankAccount::bankAccount(const bankAccount&)|
includeBankaccount.h|4|note: no known conversion for argument 1 from       'std::string {aka std::basic_string}' to 'const bankAccount&'|

我认为这可能是标题的问题? 我有点疯狂,把所有相关的标题放在每个文件上,试图让它工作。

using namespace std;

这被认为是一种糟糕的编程实践,如果你忘记了这实际上是C++语言的一部分,你会帮自己一个忙。尽管在适当的情况下会使用using namespace,但在对C++、其结构和语法有更好的技术理解之前,应避免这种情况;为了识别和理解何时可以正确使用(如果有的话)。

在你的main()中,你有:

string fileName;

C++库中没有这样的类,其名称为string。类的正确名称是std::string;然而,通过推using namespace std;上面的几行,你最终幸福地不知道这个基本的、基本的事实。

现在,在你理解了这一点之后,让我们回过头来看看你的头文件:

ifstream sourceFile;

好吧,C++库中也没有这样的类叫做ifstream,。该类的正确名称是std::ifstream。C++库中的所有类和模板都存在于std命名空间中。

但是,由于当您#include头文件时,尚未定义using namespace std;别名,因此编译器无法识别类名,并且您会收到此编译错误作为奖励。

解决方案是不在头文件中塞入using namespace std;。这只会导致更多的混乱和混乱。正确的解决方法是:

  1. 完全删除代码中的using namespace std;

  2. 随时随地使用 C++ 库中所有类的全名。将所有对stringifstream和其他所有内容的引用替换为它们的实际类名:std::stringstd::ifstream等。养成每次都显式使用std命名空间前缀的习惯。乍一看似乎很麻烦,但不久你很快就会养成这个习惯,而且你不会三思而后行。

而且你永远不会被这些编译错误所迷惑。