私がしようとしていることを正確に指定しておきたいのですが、foo-barプログラムをmain、foo.h、foo.cpp、bar.hの5つのファイルに分割する必要があります。 、bar.cpp。私のヘッダーファイル(foo.hとbar.h)は対応するクラスの宣言を含んでいますが、C++ファイル(foo.cppとbar.cpp)はクラスを定義するためのものです。C++ソースファイルを複数のファイルに分割する際のトラブル
私はVisual Studioを使用しています。これまでのところ、赤い旗を表示していた唯一のファイルは私のメインファイルです。ここに私のコードは、これまでのところで、私は私のメインのファイルにスローされるエラーが含まれます:
main.cppに
#include <iostream>
#include "foo.h"
#include "foo.cpp"
#include "bar.h"
#include "bar.cpp"
using namespace std;
int main() {
Bar b(25); /*I am getting a red flag under the 25, stating there is no constructor that can convert int to Bar*/
b.func1(); /*I'm getting a red flag under func1 and func2 stating neither of them are members of Bar*/
b.func2(34);
return 0;}
がfoo.h
#ifndef foo_h
#define foo_h
#include "foo.cpp"
class Foo {};
#endif
FOO .cpp
#ifndef foo_c
#define foo_c
#include "foo.h"
#include "bar.cpp"
private:
int data;
public:
Foo(int d) : data(d) {}
int get_data() { return data; }
virtual void func1() = 0;
virtual int func2(int d) = 0;
#endif
bar.h
#ifndef bar_h
#define bar_h
#include "bar.cpp"
#include "foo.h"
class Bar : public Foo {};
#endif
bar.cpp
#ifndef bar_c
#define bar_c
#include "bar.h"
#include "foo.h"
#include "foo.cpp"
Bar(int d) : Foo(d) {}
void func1() {
cout << "Inside func1\n";
cout << "\tData is " << get_data() << endl;
}
int func2(int d) {
cout << "Inside func2 with " << d << endl;
cout << "\tData is " << get_data() << endl;
return d;
}
#endif
私はそれを分割するまで、私のプログラムが働いていたが、今では私はそれをコンパイルしようとする私にこのメッセージを投げ続け、赤旗のカップルがあります私のメインコードで。このコンソールは、私に語ったものです:
のメンバーではありませんされていませんんが、適切なコンストラクタが
関数func1を棒にint型に変換するために存在していないが、クラスバー
関数func2のメンバーは、クラスのバー
私の質問は何ですか:私は間違っています、そして、私がやろうとしていることについて行く良い方法がありますか?
ありがとうございます。
あなたのcppファイルのみ.hファイルを含める必要はありません。ただし、.cppファイルをコンパイルし、オブジェクトファイルがリンクステージで使用可能であることを確認する必要があります。それがコンパイル単位と呼ばれる理由です。 –
cppファイルはインクルードする必要がないので、 '#ifndef'マクロブロックは必要ありません。 –