简体   繁体   中英

Using the new operator with an object's non-default constructor

Would something like:

classname* p = new classname(parameter1, parameter2, ...); 

create a pointer that points to an object initialized using a non-default constructor with signature: classname(parameter1, parameter2, ...) ?

Thanks!

对,那是正确的。



我自己不能放得更好-记住要在完成后删除它,除非您想让堆不开心!

Yes, it will. This program illustrates the concept.

#include <string>
#include <iostream>

class Foo
{
private:
    std::string name;
public:
    Foo() : name("default"){}
    Foo(std::string Name): name(Name) {}

    void Print() { std::cout << name << std::endl; }
};

int main ()
{
    Foo* foo = new Foo();
    foo->Print();
    delete foo;

    foo = new Foo("special");
    foo->Print();
    delete foo;
}

The output is:

default
special

Yes it does. but may I know how did the question came to your mind? you got some errors?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM