-1

在 C++ 中使用重载构造函数动态分配对象的语法是什么?

如果我有一个班级 Foo:

class Foo{
public:
    Foo(string str, int nbr);    // Overloaded constructor
};

第二类 Foo2(使用 Foo):

#include "Foo"
class Foo2{
public:
    Foo* myFoo;    // Wrong!
    Foo2(){
        myFoo = new Foo(myStr, myNbr);
    }
};

显示的错误如下:

调用“Foo::Foo()”没有匹配的函数

在创建 myFoo 对象指针时,如何指定它将使用Foo(string str, int nbr)构造函数,而不是Foo()构造函数。

是否可以不使用构造函数委托?

4

3 回答 3

2

您构造对象的语法是正确的。

很难确定,因为你没有告诉错误,但我猜你的问题是构造函数是private。这意味着您不能在类之外使用构造函数。

有关错误消息的编辑:

这是一个完整的编译示例。我添加了一些会产生错误的示例行:没有匹配函数调用'Foo::Foo()'。

#include <string>

class Foo{
public:
    Foo(std::string str, int nbr);
};

// empty definition
Foo::Foo(std::string str, int nbr) {}

// delegating constructor (c++11 feature)
// this would produce error: no matching function for call to 'Foo::Foo()'
//Foo::Foo(std::string str, int nbr) : Foo::Foo() {}

int main() {
    Foo* myFoo;
    myFoo = new Foo("testString", -1); // this is correct
    // trying to construct with default constructor
    //Foo myFoo2; // this would produce error: no matching function for call to 'Foo::Foo()'
    //Foo* myFoo3 = new Foo(); // so would this
}

鉴于错误,您的代码正试图在某处使用默认构造函数。

Edit2 关于您的新Foo2示例。您对 Foo* 的声明和对构造函数的调用仍然正确,如果您修复了方法可见性和缺少分号,代码应该可以编译。以下示例编译:

#include <string>

class Foo{
public:
    Foo(std::string str, int nbr);    // Overloaded constructor
};

Foo::Foo(std::string str, int nbr){}

class Foo2{
    Foo* myFoo;    // This is still correct
public:
    Foo2() {
        myFoo = new Foo("", 1);
    }
};

int main() {
    Foo2 foo2;
}
于 2014-02-27T12:06:58.667 回答
1

语法正确。由于您尚未编写完整的类定义,因此有很多可能性。1.检查是否写了默认的cnstsructor。2. 检查两个构造函数是否都在公共部分内。3. 或者,您可以更改对构造函数的调用,如下所示,

Foo* myFoo = new Foo("testString", -1);

以下代码应该可以工作。

class Foo
{

string str;
int num;
public:
    Foo(string p_str, int nbr):str(p_str),num(nbr){};    // Overloaded constructor
    Foo() {};    // Default constructor
};
于 2014-02-27T12:28:15.763 回答
-1

正确的方法是初始化每个构造函数中的成员。您可以在私有 init() 成员函数中提取它们的公共代码,并在每个构造函数中调用它,如下所示:

class Foo {
    public:
        Foo(string x);
        Foo(string x, int y);
        ...
    private:
        void init(string x, int y);
};

Foo::Foo(string x)
{
    init(x, int(x) + 3);
    ...
}

Foo::Foo(string x, int y)
{
    init(x, y);
    ...
}

void Foo::init(string x, int y)
{
    ...
} 
于 2014-02-27T12:09:29.530 回答