您构造对象的语法是正确的。
很难确定,因为你没有告诉错误,但我猜你的问题是构造函数是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;
}