2012-02-03 4 views
0

ここに私が何を持っています。私はカスタムコンストラクタを使用して、バーでFooのインスタンスを作成しようとしています。私がBarのコンストラクタからコンストラクタを呼び出そうとすると、私は外部に入り、未解決です。未解決の外部シンボル "public:class Foo __thiscall Bar :: bu(char const *)"

class Foo 
{ 
public: 
    // The custom constructor I want to use. 
    Foo(const char*); 
}; 

class Bar 
{ 
public: 
    Bar(); 
    //The instance of Foo I want to use being declared. 
    Foo bu(const char*); 
}; 

int main(int argc, char* args[]) 
{ 
    return 0; 
} 

Bar::Bar() 
{ 
    //Trying to call Foo bu's constructor. 
    bu("dasf"); 
} 

Foo::Foo(const char* iLoc) 
{ 
} 
+1

そのコードは無効です。メンバ変数を追加するときは、カスタムコンストラクタを使用するときにポインタを使用します:Foo * bu;次に、コンストラクタでインスタンスを作成します。 – peterept

+0

これはむしろリンカーの問題です。私が投稿したソースは、ここであなたの問題を解決するのに十分ではないと思います。すべてが同じ翻訳単位(ファイル)で宣言されていますか?それから、私はそれがうまくいくと思う。そうでなければ、どのファイルに格納されているかを示すソースを編集し、コンパイラとリンカの完全なコマンドラインに対応する出力を与えてください。 – Axel

+0

@peterept:私はそれが有効だと思います。Bar :: buはメンバー変数ではなくFooを返すメソッドとして宣言されています。 Bar :: Bar()では、buメソッドが呼び出され、使用されていないオブジェクトが返されます。あまり意味はありませんが、うまくいくはずです。 – Axel

答えて

0

これは、あなたが望むものはおそらくです:この宣言については

class Foo 
{ 
public: 
    // The custom constructor I want to use. 
    Foo(const char*); 
}; 

class Bar 
{ 
public: 
    Bar(); 
    //The instance of Foo I want to use being declared. 
    Foo bu; // Member of type Foo 
}; 

int main(int argc, char* args[]) 
{ 
    return 0; 
} 

Bar::Bar() : bu("dasf") // Create instance of type Foo 
{ 
} 

Foo::Foo(const char* iLoc) 
{ 
} 

Foo bu(const char*);これはconst char*を取り、Fooを返しbuという名前のメンバ関数の宣言です。未解決のシンボルエラーは、関数buを決して定義していないが、Fooのインスタンスを関数にしないためです。コメントを見た後

その他の方法:

class Foo 
{ 
public: 
    // The custom constructor I want to use. 
    Foo(const char*); 
}; 

class Bar 
{ 
public: 
    Bar(); 
    ~Bar() { delete bu;} // Delete bu 
    //The instance of Foo I want to use being declared. 
    Foo *bu; // Member of type Foo 
}; 

int main(int argc, char* args[]) 
{ 
    return 0; 
} 

Bar::Bar() : bu(new Foo("dasf")) // Create instance of type Foo 
{ 
} 

Foo::Foo(const char* iLoc) 
{ 
} 

そして他の多くの問題が多分C++ Primerのように、C++の本を取得し、あなたのコードでもありますが良いでしょう。

関連する問題