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*);这是一个名为的成员函数的声明,bu它接受 aconst char*并返回 a Foo。未解决的符号错误是因为您从未定义函数,但您想要一个不是函数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++ 的书,比如C++ Primer是个好主意。

于 2012-02-03T06:34:16.253 回答