0

これが私が持っているものです。カスタムコンストラクターを使用して、Bar内にFooのインスタンスを作成しようとしています。Barのコンストラクターからコンストラクターを呼び出そうとすると、外部で未解決になります。

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)
{
}
4

1 に答える 1

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*);という名前のメンバー関数の宣言です。未解決のシンボルエラーは、関数を定義したことがないが、関数ではないインスタンスが必要なためです。buconst char*FoobuFoo

コメントを見た後の他の方法:

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++に関する本を入手することをお勧めします。

于 2012-02-03T06:34:16.253 に答える