【问题标题】:How do I remove errors after creating .h and .cpp files for a class? C++为类创建 .h 和 .cpp 文件后如何删除错误? C++
【发布时间】:2017-03-19 01:22:48
【问题描述】:

因此,我正在学习在我的程序中使用 .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;
}

这是我的 Bankaccount.h 文件

#ifndef BANKACCOUNT_H
#define BANKACCOUNT_H
#include <iostream>
#include <fstream>
#include <string>

class bankAccount
{
public:
    bankAccount(string n);
    bankAccount();

private:
    ifstream sourceFile;
}

最后这是 Bankaccount.cpp 文件

#include "Bankaccount.h"
#include <iostream>
#include <fstream>
#include <string>

bankAccount::bankAccount(string n)
{
    sourceFile.open(n.c_str());
}

现在产生这些错误:

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

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

【问题讨论】:

  • 试试std::ifstream和std::string。
  • 类定义需要一个 ;在右大括号之后。

标签: c++ class header fstream


【解决方案1】:
using namespace std;

这被认为是a bad programming practice,如果您忘记这实际上是 C++ 语言的一部分,您会帮自己一个忙。尽管在某些情况下会使用using namespace,但在对 C++、它的结构和语法有更好的技术理解之前,应该避免这种情况;为了识别和理解什么时候可以正确使用(如果有的话)。

在你的 main() 中你有:

string fileName;

C++ 库中没有名为string 的类。该类的正确名称是std::string;但是,通过将using namespace std; 推到上面几行,您最终会幸福地没有意识到这个基本的基本事实。

现在,明白了这个之后,我们再回过头来看看你的头文件:

ifstream sourceFile;

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

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

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

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

  2. 使用 C++ 库中所有类的全名,无处不在。将所有对string、ifstream 和其他所有内容的引用替换为它们的实际类名:std::string、std::ifstream 等等。养成每次显式使用 std 命名空间前缀的习惯。一开始可能会觉得很麻烦,但你很快就会养成这个习惯,而且你不会再想了。

而且您再也不会被这类编译错误弄糊涂了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多