2010-12-16 12 views
1

私はこれをしようとすると、私は、コンパイラは、表が定義されていないことを教えC++クラスのメンバー

class Box { 
    Table* onTable; 
}; 

class Table { 
    Box* boxOnIt; 
}; 

int main() { 
    Table table; 
    Box box; 

    table.boxOnIt = &box; 
    box.onTable = &table; 

    return 0; 
} 

... C++ ...

に、Javaから来ました。 クラス定義を切り替えると、コンパイラはBoxが定義されていないことを教えてくれます

Javaでは、問題なくこのようにすることができました。 これが機能するソリューションはありますか? ありがとう...

+0

私は、クラス外からアクセスする必要がある場合は、プロパティをパブリックに宣言する必要があるとの回答はありません。クラスメンバーはC++で暗黙的にプライベートなので、'boxOnIt'や 'onTable'にアクセスしようとすると、コードからコンパイラエラーが発生するはずです。 – Kleist

答えて

2

上のクラス定義を追加します。ここでは循環依存性が必要であり、クラスのいずれかを宣言するために転送:

box.h:一般的に言えば、我々は前方の両方で宣言、例えばを使用して、BoxTable用に別のヘッダファイルを持っているだろう、ということ

// forward declaration class Box; class Table { Box* boxOnit; } // eo class Table class Box { Table* onTable } // eo class Box 

class Table; 

class Box 
{ 
    Table* table; 
}; // eo class Box 

table.h

その後

、私たちの実装に必要なファイル(.CPP)ファイルが含まれます:

box.cpp

#include "box.h" 
#include "table.h" 

table.cpp

#include "box.h" 
#include "table.h" 
+0

ありがとう、コードが動作しています。 – Mustafa

2

forward declarationsをご利用ください。ちょうどあなたの最初の文としてこれを言及:

class Table; // Here is the forward declaration 
+1

を作成し、オブジェクトごとに別々の(ヘッダー)ファイルを作成することを習慣にしてください。 box.hとtable.hを作成し、main.cppに含めます。 – RvdK

2

は、クラスボックス前にこれを追加します。

class Table; 

したがって、あなたforward declareクラス表をそれへのポインタがボックスで使用できるように。

1
class Table; 

class Box { 
    Table* onTable; 
}; 

class Table { 
    Box* boxOnIt; 
}; 

int main() { 
    Table table; 
    Box box; 

    table.boxOnIt = &box; 
    box.onTable = &table; 

    return 0; 
} 
1

次の2つのクラスのいずれかを宣言転送する必要があります。

class Table; // forward declare Table so that Box can use it. 

class Box { 
    Table* onTable; 
}; 

class Table { 
    Box* boxOnIt; 
}; 

int main() { 
    Table table; 
    Box box; 

    table.boxOnIt = &box; 
    box.onTable = &table; 

    return 0; 
} 

またはその逆を:

class Box; // forward declare Box so that Table can use it. 

class Table { 
    Box* boxOnIt; 
}; 

class Box { 
    Table* onTable; 
}; 

int main() { 
    Table table; 
    Box box; 

    table.boxOnIt = &box; 
    box.onTable = &table; 

    return 0; 
} 
0

は、あなたが持っているトップ

class Table; 

class Box { 
    Table* onTable; 
}; 

class Table { 
    Box* boxOnIt; 
}; 
+1

これは定義ではなく、先頭に必要な宣言です。 – Kleist

関連する問題