如何在为类创建 .h 和 .cpp 文件后删除错误?C++
How do I remove errors after creating .h and .cpp files for a class? C++
所以我正在学习使用类.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;
。这只会导致更多的混乱和混乱。正确的解决方法是:
完全删除代码中的
using namespace std;
。随时随地使用 C++ 库中所有类的全名。将所有对
string
、ifstream
和其他所有内容的引用替换为它们的实际类名:std::string
、std::ifstream
等。养成每次都显式使用std
命名空间前缀的习惯。乍一看似乎很麻烦,但不久你很快就会养成这个习惯,而且你不会三思而后行。
而且你永远不会被这些编译错误所迷惑。
- 如何在我从C++文件中读取后立即删除行
- 删除 XML 文件中的子节点C++
- 如何在输入新内容 c++ 之前删除文件中的所有内容
- 如何更新和删除文本文件中的特定逗号分隔值?C++
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- 将内容从第一个文件("constituencies")移动到第二个文件("temp")并在之后重命名时,我的文件被删除
- 文件模式标志"ios::app"是否用于删除文件(如果文件已存在)?
- 如何自动获取我的项目的路径并删除一些文件
- C++ VS 错误:<实验/文件系统>提供 std::experimental::文件系统的标头已被Microsoft弃用,将被删除
- 如果我删除指针,我的C++程序会意外删除系统文件吗?
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- 文件删除(使用取消链接)与释放所有磁盘空间之间的延迟
- 重命名批处理文件(删除名称中的一些符号)(python/matlab/shell)
- 如何找到字符串并使用C 文件中的文件删除它
- 使用 DEF 文件删除 dll 导出的名称
- 关闭后等待文件删除
- c++中的文件删除
- 如何共享文件删除权限时,我打开一个文件ifstream
- 典型的Win32文件删除(IDropTarget::drop)实现
- 生成文件模式规则:循环生成文件.o < - 删除生成文件依赖项