2

更新:ファイルを明確にして、質問を繰り返しましょう:

main.h

#include "other.h"

class MyClass
{
    public:
    void MyMethod();
    void AnotherMethod();

    OtherClass test;
}

main.cpp

#include "main.h"

void MyClass::MyMethod()
{
    OtherClass otherTemp;     // <--- instantitate OtherClass object
    otherTemp.OtherMethod();  // <--- in this method here, is where I want to also call MyClass::AnotherMethod()
}

void MyClass::AnotherMethod()
{
    // Some code
}

その他.h

class OtherClass
{
    public:
    void OtherMethod();
}

その他.cpp

#include "other.h"
void OtherClass::OtherMethod()
{
    // !!!! This is where I want to access MyClass::AnotherMethod(). How do I do it?
    // I can't just instantiate another MyClass object can I? Because if you look above in 
    // main.cpp, this method (OtherClass::OtherMethod()) was called from within
    // MyClass::MyMethod() already.
}

だから基本的に私が欲しいのはこれです:オブジェクトAをインスタンス化し、オブジェクトBをインスタンス化し、オブジェクトBからオブジェクトAのメソッドを呼び出します。このようなことは可能だと確信していますが、設計が悪いだけかもしれません私の分。どんな方向性でも大歓迎です。

4

4 に答える 4

3

クラスごとに 1 つの .h/.cpp を実行するものもあります。

私の.h

#ifndef MY_H
#define MY_H
#include "other.h"
class MyClass
{
    public:
    void MyMethod();

    OtherClass test;
}
#endif // MY_H

その他.h

#ifndef OTHER_H
#define OTHER_H
class OtherClass
{
    public:
    void Othermethod();
}
#endif // OTHER_H

my.cpp

#include "my.h"
void MyClass::MyMethod() { }

その他.cpp

#include "other.h"
#include "my.h"
void OtherClass::OtherMethod)()
{
   // (ab)using MyClass...
}

Visual Studio のみを使用している場合は、#pragma once代わりに#ifndef xx_h #define xx_h #endif // xx_h. EDIT:コメントが言うように、また関連するウィキペディアのページ#pragma onceも(少なくとも)GCCでサポートされています。

更新:更新された質問について、#include とは関係ありませんが、オブジェクトの受け渡しについての詳細...

MyClass には既に OtherClass の埋め込みインスタンスがありますtest。したがって、MyMethod では、おそらく次のようになります。

void MyClass::MyMethod()
{
    test.OtherMethod();
}

また、OtherMethod が MyClass インスタンスにアクセスする必要がある場合は、このインスタンスを参照またはポインターとして OtherMethod に渡します。

参照により

class OtherClass { public: void OtherMethod(MyClass &parent); }

void MyClass::MyMethod() { test.OtherMethod(*this); }

void OtherClass::OtherMethod(MyClass &parent)
{
   parent.AnotherMethod();
}

ポインターで

class OtherClass { public: void OtherMethod(MyClass *parent); }

void MyClass::MyMethod() { test.OtherMethod(this); }

void OtherClass::OtherMethod(MyClass *parent)
{
   if (parent == NULL) return;  // or any other kind of assert
   parent->AnotherMethod();
}
于 2010-07-31T17:06:26.230 に答える
2

ヘッダーではなく、C++ ソース ファイルのいずれかのクラスの外側で関数を定義します。

void OtherClass :: Othermethod() {
   // call whatever you like here
}
于 2010-07-31T16:57:21.693 に答える
2

.cpp ファイルを作成します。

#include "main.h"

void OtherClass::Othermethod()
{
    MyClass m; //ok :)
    m.MyMethod(); //also ok.
}

とにかく、実装はヘッダーに属しません。

于 2010-07-31T16:57:38.233 に答える
0

other.cpp 内に #include するだけです

于 2010-07-31T16:57:42.523 に答える