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;
}

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

他のすべてのメンバー関数と変数についても同じです。hereの指示に従おうとしました(メインと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

default-parameters は、定義を含む cpp ファイルではなく、宣言が含まれているヘッダー ファイルで宣言する必要があります。(追加の間違いは、定義でそれらを宣言することでした)。ここでいくつかのヘルプを見つけました。しかし、1 つのファイル全体に実装したのに、なぜ機能したのでしょうか。

答え:

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 に答える