编辑推荐: |
本文主要介绍了C++对象数组的定义和初始化相关知识。 希望能为大家提供一些参考或帮助。
文章来自于博客园,由火龙果Linda编辑推荐。 |
|
一、赋值初始化
1、如果类有默认构造函数
object *p = new object[3];
2、如果类没有构造函数
没有默认构造函数,有自定义的构造函数 object(contx* c,stack* s)
object *p = new object[3]{{cct,this},{cct,this},{cct,this}};
(但这个要求object构造函数前不能有explicit,否则无法将{cct,this}隐式转换成object)
或
object *p = new object[3]{object(cct,this),object(cct,this),object(cct,this)};
(但这个要求object有object::object(const object&)构造函数,否则报错:
error use of deleted function)
实例
#include <iostream>
using namespace std;
class Acct
{
public:
Acct() {
balance = 0.0;
cout << "no var create...." << endl;
}
Acct( double init_balance ,double init_cc ) {
balance = init_balance;
cc = init_cc;
cout << "with var create..." << endl;
}
~Acct(){
cout << "delete..." << endl;
}
private:
double balance;
double cc;
};
int main()
{
Acct myAcct[6];
Acct *CheckingAcct = new Acct[3];
Acct *SavingsAcct = new Acct[3] {Acct(34.98,2), Acct(131.4,2), Acct(521.1,2)};
Acct *SavingsAcct2 = new Acct[3] {{34.98,2}, {131.4,2}, {521.1,2}};
delete [] CheckingAcct;
delete [] SavingsAcct ;
}
|
二、用指针数组
typedef Acct* ACCP; //ACCP是个指向EquipmentPiece的指针
ACCP bestPieces[10]; //等同于 ACCP *bestPieces = new
ACCP[10];
//然后初始化 for(int i = 0; i < 10; i++){ bestPieces[i]
= new Acct(balance ,cc ) ; }
注意: 要记得将此数组所指的所有对象删除。如果忘了会产生资源泄露。还有就是该方法与对象数组相比需要额外内存用于存放指针。(过度使用内存
这一问题可以避免,见第三种方法)
三、上面的只适合静态数组,动态数组用C++11的allocator
对于allocator类,请看 另一篇blog C++ allocator类学习理解
请看一下代码关于使用如何实现无默认构造函数,动态实例化对象数组的allocator方法
#include <memory>
#include <iostream>
using namespace std;
class Animal
{
public:
#if 0
Animal() : num(0)
{
cout << "Animal constructor default" << endl;
}
#endif
Animal(int _num) : num(_num)
{
cout << "Animal constructor param" << endl;
}
~Animal()
{
cout << "Animal destructor" << endl;
}
void show()
{
cout << this->num << endl;
}
private:
int num;
};
int main()
{
allocator<Animal> alloc;
Animal *a = alloc.allocate(5);
alloc.construct(a, 1);
alloc.construct(a + 1);
alloc.construct(a + 2, 3);
alloc.construct(a + 3);
alloc.construct(a + 4, 5);
a->show();
(a + 1)->show();
(a + 2)->show();
(a + 3)->show();
(a + 4)->show();
for (int i = 0; i < 5; i++)
{
alloc.destroy(a + i);
}
alloc.deallocate(a, 5);
cin.get();
return 0;
}
如果构造函数是多个参数,则可以这样:
alloc.construct(a, Animal(50,"dog"));
alloc.construct(a + 1,Animal(30,"cat"));
alloc.construct(a + 2,Animal(100,"goal"));
alloc.construct(a + 3,Animal(65,"cow"));
alloc.construct(a + 4,Animal(5,"bird"));
|
C++中若类中没有默认构造函数,如何使用对象数组
#include "allocator.hpp"
#include <iostream>
#include <memory>
#include <string>
#include <vector>
namespace allocator_ {
int test_allocator_1()
{
std::allocator<std::string> alloc;
int n{ 5 };
auto const p = alloc.allocate(n);
auto q = p;
alloc.construct(q++);
alloc.construct(q++, 10, 'c');
alloc.construct(q++, "hi");
std::cout << *p << std::endl;
std::cout << p[0] << std::endl;
std::cout << p[1] << std::endl;
std::cout << p[2] << std::endl;
while (q != p) {
alloc.destroy(--q);
}
alloc.deallocate(p, n);
return 0;
}
int test_allocator_2()
{
std::vector<int> vi{ 1, 2, 3, 4, 5 };
std::allocator<int> alloc;
auto p = alloc.allocate(vi.size() * 2);
auto q = std::uninitialized_copy(vi.begin(), vi.end(), p);
std::uninitialized_fill_n(q, vi.size(), 42);
return 0;
}
int test_allocator_3()
{
std::cout << std::endl;
std::allocator<int> intAlloc;
std::cout << "intAlloc.max_size(): " << intAlloc.max_size() << std::endl;
int* intArray = intAlloc.allocate(100);
std::cout << "intArray[4]: " << intArray[4] << std::endl;
intArray[4] = 2011;
std::cout << "intArray[4]: " << intArray[4] << std::endl;
intAlloc.deallocate(intArray, 100);
std::cout << std::endl;
std::allocator<double> doubleAlloc;
std::cout << "doubleAlloc.max_size(): " << doubleAlloc.max_size() << std::endl;
std::cout << std::endl;
std::allocator<std::string> stringAlloc;
std::cout << "stringAlloc.max_size(): " << stringAlloc.max_size() << std::endl;
std::string* myString = stringAlloc.allocate(3);
stringAlloc.construct(myString, "Hello");
stringAlloc.construct(myString + 1, "World");
stringAlloc.construct(myString + 2, "!");
std::cout << myString[0] << " " << myString[1] << " " << myString[2] << std::endl;
stringAlloc.destroy(myString);
stringAlloc.destroy(myString + 1);
stringAlloc.destroy(myString + 2);
stringAlloc.deallocate(myString, 3);
std::cout << std::endl;
return 0;
}
int test_allocator_4()
{
std::allocator<int> a1;
int* a = a1.allocate(1);
a1.construct(a, 7);
std::cout << a[0] << '\n';
a1.deallocate(a, 1);
std::allocator<std::string> a2;
decltype(a1)::rebind<std::string>::other a2_1;
std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2;
std::string* s = a2.allocate(2);
a2.construct(s, "foo");
a2.construct(s + 1, "bar");
std::cout << s[0] << ' ' << s[1] << '\n';
a2.destroy(s);
a2.destroy(s + 1);
a2.deallocate(s, 2);
return 0;
}
}
|
C++中std::allocator的使用_网络资源是无限的
更多详情
有默认的构造函数:
如果一个类有默认的构造函数,使用new动态实例化一个对象数组不是件难事,如下代码:
class animal
{
public:
animal():num(0)
{}
~animal()
{}
private:
int num;
};
Animal *ani = new Animal[5];
delete[]ani;
|
然而 new Obj[n]的形式仅仅适用于不需传入实参的默认构造函数,否则编译器报错。
没有默认构造函数|初始化对象数组的同时指定参数
想要初始化对象数组的同时指定各个构造函数的参数,有以下几种解决途径:
静态数组
1.若初始化对象数组时已知其size,使用诸如 new Obj[n]{(),(),...()} 的形式,大括号内每个小括号对应每个对象的构造函数参数:
class Array1D
{
public:
Array1D(int len2)
:len2D(len2)
{
plist = new T[len2];
for (int i = 0; i < len2; i++)
plist[i] = static_cast<T>(0);
}
~Array1D()
{
if (nullptr != plist)
delete[] plist;
}
private:
T* plist;
int len2D;
};
pArray1D = new Array1D[2]{(1),(2)}
构造函数有多个参数时:
pArray1D = new Array1D[2]{{1,100},{2,199}}
|
动态数组
2.若初始化对象数组时未知其size,需要把分配内存和构建对象的动作分开。可借助C++11的allocator。先使用allocate分配内存并用指针记录这块空间;然后用construct方法对指针所指向内存进行对象构建;当然不再使用对象时用destory方法析构对象;注意,既然分配内存和构建对象动作已分开,那么析构对象和释放内存也要配对,用deallocate释放内存:
class Array2D
{
public:
class Array1D
{...};
Array2D(int len1, int len2)
:len1D(len1)
{
pArray1D = alloc.allocate(len1);
for (int i = 0; i < len1; i++) {
alloc.construct(pArray1D + i, len2);
}
}
~Array2D()
{
for (int i = 0; i < len1D; i++) {
alloc.destroy(pArray1D + i);
}
alloc.deallocate(pArray1D, len1D);
}
private:
Array1D* pArray1D;
int len1D;
allocator<Array1D> alloc;
};
|
3.使用operator new和placement new,与allocator原理类似,分四步走:
class animal
{
public:
animal():num(0)
{}
animal(int _num):num(_num)
{}
~animal()
{}
void show() {
cout << num << endl;
}
void* operator new(size_t size, void* p)
{
return p;
}
private:
int num;
};
int main(int argc, char* argv[])
{
{
void* p = operator new(5 * sizeof(animal));
animal* a = static_cast<animal*>(p);
for (int i = 0; i < 4; i++)
{
new(a + i) animal(i);
}
new(a + 4) animal;
for (int i = 0; i < 5; i++) {
(a + i)->show();
}
for (int i = 0; i < 5; i++) {
(a + i)->~animal();
}
delete[] p;
}
return 0;
}
参考:https:
|
原文链接:https://blog.csdn.net/brahmsjiang/article/details/88347005
#include <memory>
#include <iostream>
using namespace std;
class Animal
{
public:
#if 0
Animal() : num(0)
{
cout << "Animal constructor default" << endl;
}
#endif
Animal(int _num,string _name) : num(_num),name(_name)
{
cout << "Animal constructor param" << endl;
}
~Animal()
{
cout << "Animal destructor" << endl;
}
void show()
{
cout <<"num:"<<this->num << endl;
cout <<"name:"<< this->name << endl;
}
private:
int num;
string name;
};
int main()
{
allocator<Animal> alloc;
Animal *a = alloc.allocate(5);
alloc.construct(a, Animal(50,"dog"));
alloc.construct(a + 1,Animal(30,"cat"));
alloc.construct(a + 2,Animal(100,"goal"));
alloc.construct(a + 3,Animal(65,"cow"));
alloc.construct(a + 4,Animal(5,"bird"));
a->show();
(a + 1)->show();
(a + 2)->show();
(a + 3)->show();
(a + 4)->show();
for (int i = 0; i < 5; i++)
{
alloc.destroy(a + i);
}
alloc.deallocate(a, 5);
cin.get();
return 0;
}
|
|