在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()
构造函数。
是否可以不使用构造函数委托?
您构造该对象的语法是正确的。
由于您没有告诉错误,因此很难确定,但是我的猜测是您的问题是构造函数是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
}
鉴于该错误,您的代码正在尝试在某处使用默认构造函数。
有关您的新Foo2
示例的Edit2 。您对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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句