复制构造函数到数组的语法

时间:2013-09-12 11:30:16

标签: c++ arrays pointers copy-constructor

我正在尝试创建一个指向类的指针的指针。 我试图不调用默认的c'tor,因为他推进了静态整数。 所以我使用copy c'tor来避免推进var,唯一的问题是我不确定什么是正确的语法。 这是代码:

#include <stdio.h>


class A
{
    static int x;
    int m_x;
    int m_age;
public:
    A(){m_x=x;x++;m_age=0;}
    A(const A& that ){m_age =that.m_age; m_x = that.m_x;}
    A(int age){m_age = age;}
    int getX(){return m_x;}
    int getStaticX(){return x;}
    int getAge(){return m_age;}
};

int A::x = 0 ;

int main()
{
    int size = 15;
    A *tmp = new A[size]();
    A *tmp1;

    //I'm not sure here what is the currect symtax to do this:
    for (int i = 0; i< size;i++)
    {
        tmp1[i] = new A(tmp[i]);
    }
    ////////////////////////////////////////////////////        


    for (int i =0 ;i<size;i++)
    {
            //I want the same result in both prints
        printf("tmp1:%d\n",i);
        printf("age:%d  m_int:%d  static:%d\n",tmp1[i].getAge(),tmp1[i].getX(),tmp1[i].getStaticX());
        printf("tmp:%d\n",i);
        printf("age:%d  m_int:%d  static:%d\n",tmp[i].getAge(),tmp[i].getX(),tmp[i].getStaticX());
        printf("EOF\n\n");
    }


    return 0;
}

谢谢!

4 个答案:

答案 0 :(得分:0)

您可以阅读并获得复制构造函数herehere的示例并执行:

A(A& that ){m_age =that.m_age; m_x = that.m_x;}

例如。

但问题是您分配了tmp但未分配tmp1因此这是对未分配内存的分配

答案 1 :(得分:0)

好吧,我已经设法达到了这样:

int main()
{
    int size = 15;
    A *tmp = new A[size]();
    A *tmp1 = tmp;

    for (int i =0 ;i<size;i++)
    {
        printf("tmp1:%d\n",i);
        printf("age:%d  m_int:%d  static:%d\n",tmp1[i].getAge(),tmp1[i].getX(),tmp1[i].getStaticX());
        printf("tmp:%d\n",i);
        printf("age:%d  m_int:%d  static:%d\n",tmp[i].getAge(),tmp[i].getX(),tmp[i].getStaticX());
        printf("EOF\n\n");
    }


    return 0;
}

答案 2 :(得分:0)

一种方法是分配单元化内存并构建对象:

#include <memory>

A* tmp = new A[size]();
std::pair<A*,std::ptrdiff_t> buf = std:get_temporary_buffer(size);
assert(buf.second == size); // the buffer returned might be smaller than requested

A* tmp1 = buf.first;
std::uninitialized_copy(tmp, tmp+size, tmp1);

请注意,遗憾的是,你的课程已经破了。请遵守The rule of three并实现赋值运算符和析构函数,并根据需要减少计数器。

答案 3 :(得分:0)

A * tmp = new Asize; //创建由Ai指出的15个A对象。这些15个对象在创建时使用 new operator call默认构造函数 15次。

因此,您将获得增加的输出。相反,你应该使用

   int max_size = 15;         
   A *tmp1[size];                
   for (int i = 0; i< max_size;i++)
          tmp1[i] = &tmp[i];  

我认为这个解决方案可以解决。

相关问题