我正在尝试创建一个指向类指针的指针。
我正在尝试不调用默认的c'tor,因为他会推进静态整数。
因此,我使用复制c'tor来避免超前变量,唯一的问题是我不确定什么是正确的语法。
这是代码:

#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;
}


谢谢!

最佳答案

您可以阅读并获得复制构造函数herehere的示例,然后执行以下操作:

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


例如。

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

09-10 04:39
查看更多