您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码:  验证码,看不清楚?请点击刷新验证码 必填



  求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Model Center   Code  
会员   
   
 
     
   
 
 订阅
C++对象数组的定义和初始化
 
 
  314  次浏览      18 次
 2023-12-25
 
编辑推荐:
本文主要介绍了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:
    // Define default constructor and a constructor that accepts
    //  an initial balance.
    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 "CAnimal.h"
#include <memory>
#include <iostream>

using namespace std;

class Animal
{
public:
#if 0        //即使为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;
};

/*
    由于allocator将内存空间的分配和对象的构建分离
    故使用allocator分为以下几步:
    1.allocator与类绑定,因为allocator是一个泛型类
    2.allocate()申请指定大小空间
    3.construct()构建对象,其参数为可变参数,所以可以选择匹配的构造函数
    4.使用,与其它指针使用无异
    5.destroy()析构对象,此时空间还是可以使用
    6.deallocate()回收空间
*/

int main()
{
    allocator<Animal> alloc;        //1.
    Animal *a = alloc.allocate(5);    //2.

    //3.
    /*void construct(U* p, Args&&... args);
   在p指向的位置构建对象U,此时该函数不分配空间,pointer p是allocate分配后的起始地址
   constructor将其参数转发给相应的构造函数构造U类型的对象,相当于 ::new ((void*) p) 
   U(forward<Args> (args)...);
   */
    alloc.construct(a, 1);
    alloc.construct(a + 1);
    alloc.construct(a + 2, 3);
    alloc.construct(a + 3);
    alloc.construct(a + 4, 5);

    //4.
    a->show();
    (a + 1)->show();
    (a + 2)->show();
    (a + 3)->show();
    (a + 4)->show();

    //5.
    for (int i = 0; i < 5; i++)
    {
        alloc.destroy(a + i);

    }
    //对象销毁之后还可以继续构建,因为构建和内存的分配是分离的
    //6.
    alloc.deallocate(a, 5);

    cin.get();
    return 0;
}

如果构造函数是多个参数,则可以这样:
  //3.
    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_ {
 
 
// reference: C++ Primer(Fifth Edition) 12.2.2
int test_allocator_1()
{
	std::allocator<std::string> alloc; // 可以分配string的allocator对象
	int n{ 5 };
	auto const p = alloc.allocate(n); // 分配n个未初始化的string
 
	auto q = p; // q指向最后构造的元素之后的位置
	alloc.construct(q++); // *q为空字符串
	alloc.construct(q++, 10, 'c'); // *q为cccccccccc
	alloc.construct(q++, "hi"); // *q为hi
 
	std::cout << *p << std::endl; // 正确:使用string的输出运算符
	//std::cout << *q << std::endl; // 灾难:q指向未构造的内存
	std::cout << p[0] << std::endl;
	std::cout << p[1] << std::endl;
	std::cout << p[2] << std::endl;
 
	while (q != p) {
		alloc.destroy(--q); // 释放我们真正构造的string
	}
 
	alloc.deallocate(p, n);
 
	return 0;
}
 
int test_allocator_2()
{
	std::vector<int> vi{ 1, 2, 3, 4, 5 };
 
	// 分配比vi中元素所占用空间大一倍的动态内存
	std::allocator<int> alloc;
	auto p = alloc.allocate(vi.size() * 2);
	// 通过拷贝vi中的元素来构造从p开始的元素
	/* 类似拷贝算法,uninitialized_copy接受三个迭代器参数。前两个表示输入序列,第三个表示
	这些元素将要拷贝到的目的空间。传递给uninitialized_copy的目的位置迭代器必须指向未构造的
	内存。与copy不同,uninitialized_copy在给定目的位置构造元素。
	类似copy,uninitialized_copy返回(递增后的)目的位置迭代器。因此,一次uninitialized_copy调用
	会返回一个指针,指向最后一个构造的元素之后的位置。
	*/
	auto q = std::uninitialized_copy(vi.begin(), vi.end(), p);
	// 将剩余元素初始化为42
	std::uninitialized_fill_n(q, vi.size(), 42);
 
	return 0;
}
 
 
// reference: http://www.modernescpp.com/index.php/memory-management-with-std-allocator
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;
}
 
//
// reference: http://en.cppreference.com/w/cpp/memory/allocator
int test_allocator_4()
{
	std::allocator<int> a1;   // default allocator for ints
	int* a = a1.allocate(1);  // space for one int
	a1.construct(a, 7);       // construct the int
	std::cout << a[0] << '\n';
	a1.deallocate(a, 1);      // deallocate space for one int
 
	// default allocator for strings
	std::allocator<std::string> a2;
 
	// same, but obtained by rebinding from the type of a1
	decltype(a1)::rebind<std::string>::other a2_1;
 
	// same, but obtained by rebinding from the type of a1 via allocator_traits
	std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2;
 
	std::string* s = a2.allocate(2); // space for 2 strings
 
	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;
}
 
} // namespace allocator_

 

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
    class Array1D
    {...};
 
    //Array2D
    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[])
{
    {
        // operator new
        void* p = operator new(5 * sizeof(animal));
        animal* a = static_cast<animal*>(p);
        // placement new, constructor
        for (int i = 0; i < 4; i++)
        {
            new(a + i) animal(i);
        }
        new(a + 4) animal;
        // use
        for (int i = 0; i < 5; i++) {
            (a + i)->show();
        }
        // destructor
        for (int i = 0; i < 5; i++) {
            (a + i)->~animal();
        }
        // delete
        delete[] p;
    }
    return 0;
}
参考:https://www.cnblogs.com/SimonKly/p/7819147.html

 

原文链接:https://blog.csdn.net/brahmsjiang/article/details/88347005

//#include "CAnimal.h"
#include <memory>
#include <iostream>

using namespace std;

class Animal
{
public:
#if 0       //即使为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;
};

/*
    由于allocator将内存空间的分配和对象的构建分离
    故使用allocator分为以下几步:
    1.allocator与类绑定,因为allocator是一个泛型类
    2.allocate()申请指定大小空间
    3.construct()构建对象,其参数为可变参数,所以可以选择匹配的构造函数
    4.使用,与其它指针使用无异
    5.destroy()析构对象,此时空间还是可以使用
    6.deallocate()回收空间
*/

int main()
{
    allocator<Animal> alloc;        //1.
    Animal *a = alloc.allocate(5);    //2.

    //3.
    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"));

    //4.
    a->show();
    (a + 1)->show();
    (a + 2)->show();
    (a + 3)->show();
    (a + 4)->show();

    //5.
    for (int i = 0; i < 5; i++)
    {
        alloc.destroy(a + i);
    }
    //对象销毁之后还可以继续构建,因为构建和内存的分配是分离的
    //6.
    alloc.deallocate(a, 5);

    cin.get();
    return 0;
}

 

 

   
314 次浏览       18
相关文章

深度解析:清理烂代码
如何编写出拥抱变化的代码
重构-使代码更简洁优美
团队项目开发"编码规范"系列文章
相关文档

重构-改善既有代码的设计
软件重构v2
代码整洁之道
高质量编程规范
相关课程

基于HTML5客户端、Web端的应用开发
HTML 5+CSS 开发
嵌入式C高质量编程
C++高级编程

最新活动计划
MBSE(基于模型的系统工程)4-18[北京]
自然语言处理(NLP) 4-25[北京]
基于 UML 和EA进行分析设计 4-29[北京]
以用户为中心的软件界面设计 5-16[北京]
DoDAF规范、模型与实例 5-23[北京]
信息架构建模(基于UML+EA)5-29[北京]
 
 
最新文章
.NET Core 3.0 正式公布:新特性详细解读
.NET Core部署中你不了解的框架依赖与独立部署
C# event线程安全
简析 .NET Core 构成体系
C#技术漫谈之垃圾回收机制(GC)
最新课程
.Net应用开发
C#高级开发技术
.NET 架构设计与调试优化
ASP.NET Core Web 开发
ASP.Net MVC框架原理与应用开发
成功案例
航天科工集团子公司 DotNet企业级应用设计与开发
日照港集 .NET Framewor
神华信 .NET单元测试
台达电子 .NET程序设计与开发
神华信息 .NET单元测试