C++如何用参数化构造函数实例化对象
C++ How to instantiate an object with parameterised constructor?
我对C++中的参数化构造函数有一些理解问题。如果我有一个有一个构造函数的类,它有两个函数参数,我如何在另一个类头文件中实例化它?
例如:
public:
MyFunction myfunction(param1, param2); //makes an error
如何声明这样的对象?
您需要在类声明中写入MyFunction myfunction;
。
然后,在myfunction
所属类的构造函数的成员初始化器列表中,写入
/*Your constructor here*/ : myfunction(param1, param2)
{
/*the constructor body*/
}
冒号后面的位是成员初始化程序列表。param1
和param2
显然是该构造函数的参数。
您有几种方法:
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
}
};
编辑:添加了一个智能指针以遵循三规则。
相关文章:
- 如何使用非默认构造函数实例化模板化类
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 我们可以用参数化构造函数初始化结构的数组吗?
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- C++ - 使用另一个类的构造函数实例化一个对象
- 类内初始化与构造函数初始化列表的顺序
- 在保证复制的世界中构造函数实例化
- 防止复制构造函数实例化 C++11 类"deleting"
- 为构造函数初始化引用实例变量提供默认值
- C 调用模板构造函数实例化
- C++.对象使用错误的构造函数实例化
- C++如何用参数化构造函数实例化对象
- 为什么无法使用复制构造函数实例化"non const"而可以在没有复制构造函数的情况下实例化配对?
- C++中函数返回的值是右值吗?无法使用复制/移动构造函数初始化实例
- 用自定义构造函数初始化c++类的实例作为Objective C类成员
- C++:当类被模板化时,如何在使用默认构造函数实例化后将输入放入对象中
- 如何使用已知的非默认构造函数实例化未知大小的可变参数元组