C++如何用参数化构造函数实例化对象

C++ How to instantiate an object with parameterised constructor?

本文关键字:构造函数 实例化 对象 参数 何用 C++      更新时间:2023-10-16

我对C++中的参数化构造函数有一些理解问题。如果我有一个有一个构造函数的类,它有两个函数参数,我如何在另一个类头文件中实例化它?

例如:

public:
      MyFunction myfunction(param1, param2); //makes an error

如何声明这样的对象?

您需要在类声明中写入MyFunction myfunction;

然后,在myfunction所属类的构造函数的成员初始化器列表中,写入

/*Your constructor here*/ : myfunction(param1, param2)
{
    /*the constructor body*/
}

冒号后面的位是成员初始化程序列表。param1param2显然是该构造函数的参数

您有几种方法:

struct P
{
    P(int a, int b) :a(a), b(b){}
    int a;
    int b;
};
struct S
{
    S() : p1(4, 2) {} // initializer list
    P p1;
    P p2{4, 2}; // since c++11
    P p3 = P(4, 2); // since c++11
};

一个选项有一个预先声明和一个指向类的指针。

classA.h
class A
{
    public:
    A(a,b);
};
classB.h
class A;
class B{
    public:
    A* foo;
    B();
    ~B();
}
classB.cpp
#include classA.h
#include classB.h
B()
{
    foo=new A(a,b);
}
~B()
{
    delete(foo);
}

据我所知,问题是MyFunction只有一个构造函数,只接受两个参数。

您可以使用指向该对象的指针,然后在构造函数中初始化它:

#include <memory>
class Something {
    public:
        std::shared_ptr<MyFunction> data;
        Something(int par1, int par2) {
            data = std::shared_ptr<MyFunction>(new MyFunction(par1, par2)); // here you go!
        }
        ~Something() {
            //delete data; no need to do this now
        }
};

编辑:添加了一个智能指针以遵循三规则。