0

[编辑:]

问题似乎属于采用默认参数的函数。在不分离 *.h *.cpp 和主文件的情况下,它可以像我实现的那样工作:

void foo(double db;);                  // deklaration
void foo(double db = 4){ cout << db;}  // definition
int main(){
    foo();                             // usage
    return 1;
}

但是,如果我将 deklaration (-> *.h)、定义 (-> *.cpp) 和用法 (-> main) 分开,编译突然返回一个错误提示,没有函数 foo(void),因为它无法识别有一个默认参数。对此有什么建议吗?

[/编辑]

我写了一个 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_ */

我输入了class-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

和所有其他成员函数和变量相同。我尝试按照此处的说明进行操作(我只在 main 和 my_class.cpp 中放置了“my_class.h”,但随后它没有在 Eclipse 和命令行中编译(当然,还包含了 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 很陌生,但我没有看到。我试图让我的问题和信息尽可能简短。

4

1 回答 1

0

默认参数需要在头文件中声明,因为它包含声明,而不是在包含定义的 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.

为了解释我自己:

我考虑回答我的问题,因为它可以更好地概述整个问题,并且该问题现在不会显示为未回答。读完后我认为这是正确的做法。

于 2013-08-14T12:40:49.583 回答