我有这个代码:
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
writeFile();
}
int writeFile ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?它给了我错误:
1>------ Build started: Project: FileRead, Configuration: Debug Win32 ------
1> file.cpp
1>e:\documents and settings\row\my documents\visual studio 2010\projects\fileread\fileread\file.cpp(8): error C3861: 'writeFile': identifier not found
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Run Code Online (Sandbox Code Playgroud)
这只是一个简单的功能.我正在使用Visual Studio 2010.
Tud*_*dor 60
有两种解决方案.您可以将方法放在调用它的方法之上:
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int writeFile ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
int main()
{
writeFile();
}
Run Code Online (Sandbox Code Playgroud)
或者宣布原型:
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int writeFile();
int main()
{
writeFile();
}
int writeFile ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
需要声明的原型你的writeFile功能,在实际使用之前:
int writeFile( void );
int main( void )
{
...
Run Code Online (Sandbox Code Playgroud)
这是C ++有一个奇怪规则的地方。在能够编译对函数的调用之前,编译器必须知道函数名称,返回值和所有参数。这可以通过添加“原型”来完成。就您而言,这仅意味着在main以下行之前添加:
int writeFile();
Run Code Online (Sandbox Code Playgroud)
这告诉编译器存在一个名为的函数writeFile,该函数将在某处定义,该函数返回,int并且不接受任何参数。
或者,您可以先定义函数writeFile,然后再定义,main因为在这种情况下,编译器main已经知道您的函数。
请注意,并不总是需要事先了解被调用函数的要求。例如,对于内联定义的类成员,则不需要...
struct Foo {
void bar() {
if (baz() != 99) {
std::cout << "Hey!";
}
}
int baz() {
return 42;
}
};
Run Code Online (Sandbox Code Playgroud)
在这种情况下,bar即使编译器依赖于baz源代码中稍后声明的函数,也可以毫无问题地分析其定义。