如何在C++中使用参数化构造函数初始化对象数组
对象数组:
当定义一个类时,只有对象的说明定义;没有内存或存储分配。要使用在类中定义的数据和访问函数,需要创建对象。
语法:
ClassName ObjectName[number of objects];
使用带参数构造函数初始化对象数组的不同方法:
1. 使用一组函数调用作为数组元素: 这就像普通的数组声明一样,但这里我们使用构造函数的函数调用作为该数组的元素进行初始化。
#include <iostream>
using namespace std;
class Test {
// 私有变量。
private:
int x, y;
public:
// 带参数构造函数
Test(int cx, int cy)
{
x = cx;
y = cy;
}
// 将两个数相加的方法
void add() { cout << x + y << endl; }
};
int main()
{
// 使用带参数构造函数的函数调用初始化3个对象数组元素。
Test obj[] = { Test(1, 1), Test(2, 2), Test(3, 3) };
// 对每个三个元素应用add()方法。
for (int i = 0; i < 3; i++) {
obj[i].add();
}
return 0;
}
2. 使用malloc() : 为了避免调用非参数化构造函数,使用malloc()方法。“malloc”或“内存分配”方法在C++中用于动态分配指定大小的单个大内存块。它返回一个void类型的指针,可以转换为任何形式的指针。
#include <iostream>
#define N 5
using namespace std;
class Test {
// 私有变量
int x, y;
public:
// 带参数构造函数
Test(int x, int y)
{
this->x = x;
this->y = y;
}
// 打印函数
void print() { cout << x << " " << y << endl; }
};
int main()
{
// 使用malloc()分配大小为N的动态数组
Test* arr = (Test*)malloc(sizeof(Test) * N);
// 对数组每个索引调用构造函数
for (int i = 0; i < N; i++) {
arr[i] = Test(i, i + 1);
}
// 打印数组内容
for (int i = 0; i < N; i++) {
arr[i].print();
}
return 0;
}
输出:
0 1
1 2
2 3
3 4
4 5
3. 使用new关键字: new操作符表示对堆上的内存分配的请求。如果有足够的内存可用,new运算符将初始化内存并返回新分配和初始化内存的地址给指针变量。在这里,指针变量是数据类型的指针。数据类型可以是任何内置数据类型,包括数组或任何用户定义的数据类型,包括结构和类。
对于动态初始化,new关键字需要非参数化构造函数,如果我们添加了带参数的构造函数,则需要使用一个虚拟的构造函数。
#include <iostream>
#include <vector>
using namespace std;
class Test {
// private variables
int x, y;
public:
// parameterized constructor
Test(int x, int y)
: x(x)
, y(y)
{
}
// function to print
void print() { cout << x << " " << y << endl; }
};
int main() {
// declaring vector of type
// class Test
vector<Test> v;
// calling constructor for
// each index of vector
for (int i = 0; i < 5; i++) {
v.push_back(Test(i, i + 1));
}
// printing vector elements
for (int i = 0; i < 5; i++) {
v[i].print();
}
return 0;
}
输出:
0 1
1 2
2 3
3 4
4 5
#include <iostream>
#include <vector>
#define N 5
using namespace std;
class Test {
// 私有变量
int x, y;
public:
// 参数化构造函数
Test(int x, int y)
: x(x)
, y(y)
{
}
// 打印函数
void print() { cout << x << " " << y << endl; }
};
int main()
{
// 类型为 Test 的向量
vector<Test> v;
// 将对象插入到向量的末尾
for (int i = 0; i < N; i++)
v.push_back(Test(i, i + 1));
// 打印对象内容
for (int i = 0; i < N; i++)
v[i].print();
return 0;
}
输出:
0 1
1 2
2 3
3 4
4 5