编辑:
这个问题似乎属于采用默认参数的函数。在不分离*.h *.cpp和主文件的情况下,它在我实现如下内容时工作:
void foo(double db;); // deklaration
void foo(double db = 4){ cout << db;} // definition
int main(){
foo(); // usage
return 1;
}但是,如果我将deklaration (-> *.h)、definition (-> *.cpp)和usage (-> main)分离,编译突然返回一个错误通知,则不存在函数foo(void),因为它不承认存在默认参数。有什么建议吗?
/EDIT
我编写了一个c++程序,以某种方式运行:
#include <iostream>
/* other includes */
using namespace std;
class my_class
{
private:
/* variables */
public:
/* function deklarations (just some short ones are only defined not declared) */
};
ostream& operator<<(ostream &out, my_class member);
/* Definition of the member functions and of the not-member-function */
int main()
{
/*some trial codes of member-functions */
return 1;
}在一个完整的文件中,所有文件都在Eclipse中编译得很好,并且工作正常。现在,我还想尝试在一个主文件、类头文件和类cpp文件中分离(称为"my_class.h“和my_class.cpp)。
为此,我输入了类标题:
#ifndef MY_CLASS_H_
#define MY_CLASS_H_
#include <iostream>
/* other includes */
using namespace std;
class my_class
{
/* ... */
};
ostream & operator<<(ostream &out, my_class member);
#endif /* MY_CLASS_H_ */我上了课-cpp:
/* Definition of the member functions and of the not-member-function */我的主要观点是:
#include <iostream>
#include "my_class.h"
#include "my_class.cpp"
int main()
{
/*some trial codes of member-functions */
return 1;
}此版本使用命令行中的g++命令进行编译:
g++ -o main.exe main.cpp但是它没有在Eclipse中编译。在这里,它给了我错误:
...\my_class.cpp:11.1: error: 'my_class' does not name a type所有其他成员函数和变量也是如此。我试着遵循这里的指示(我只将"my_class.h“放在main和my_class.cpp中,但是它没有在Eclipseand命令行中编译(当然,还包括my_class.cpp ))。Eclipse给了我一个错误,使我相信Eclipse没有看到"my_class.cpp":
...\main.cpp:288:47: error: no matching function for call to 'my_class::foo(...)'其中foo代表"my_class.cpp“文件中的第一个成员函数解密。首先,它也给出了构造函数的错误,但是当我将它的定义直接放入*.h文件时,它工作得很好。(这就是为什么我认为,它没有看到"my_class.cpp“文件)
我想我可能错过了一些非常琐碎的东西,因为我对Eclipse非常陌生,但我没有看到它。我尽量使我的问题和信息尽量简短。
发布于 2013-08-14 12:40:49
默认参数需要在头文件中声明,因为它包含声明,而不是在包含定义的cpp文件中。(另一个错误是在定义中宣布它们)。找到了一些帮助这里。但是为什么它要工作,因为我在一个文件中实现了它?
If default-parameter is in the cpp-file, the main file does not see it as
it looks only into the header-file
But if the whole code is included in just one file, the default-value
can be found in the definition too.来解释我自己:
我考虑过回答我的问题,因为它更好地概括了整个问题,现在问题不再是没有答案的。在阅读了这之后,我认为这是正确的方法。
https://stackoverflow.com/questions/18210850
复制相似问题