在复制构造函数中分配和初始化

时间:2014-05-26 14:33:43

标签: c++ new-operator

在下面的代码中,我如何同时分配和初始化pt。我所知道的是new分配但也初始化。

Grid.h

class Grid
{
    int nPt;
    double* pt;
};

Grid.cpp

Grid::Grid (const Grid& g)
{
    pt = new double [nPt];
    for (int i=0; i<nPt; ++i)
    {
        pt[i] = g.pt[i];
    }
}

2 个答案:

答案 0 :(得分:0)

comment by Mat可能暗示:

<强> Grid.h

class Grid
{
public:
    Grid (const Grid& g);
    std::vector<double> pt;
    // ... some more members of your grid?
};

Grid.cpp

Grid::Grid (const Grid& g): pt(g.pt) 
{
    // ... manage other members if any
}

但如果我们认为三条规则(如mentioned by πάντα ῥεῖ)更可能是这样的:

<强> Grid.h

class Grid
{
public:
    std::vector<double> pt;
    // ... some more members of your grid?
};

Grid.cpp

// (nothing to do)

...如果到目前为止您还没有其他任何想要使用Grid类的内容,那么最好使用普通向量。

BTW:如果您正在搜索nPtpt.size()是您的新朋友: - )

答案 1 :(得分:0)

是的,你可以在数组中做到这一点,但前提是必须这样做。 否则,按照其他人的建议去寻找载体。 这是我在代码中的答案:

#include <iostream>
using namespace std;

int main() {

//unitialise == garbage
cout << "*** Unitialised ***\n";
int* p1 = new int[3];
for(int i = 0; i < 3; i++)
    cout << i << "\t" << p1[i] << endl;

// initialise individual elements
cout << "*** Initialise individual elements ***\n";
int* p2 = new int[3] { 1, 2, 3 };
for(int i = 0; i < 3; i++)
    cout << i << "\t" << p2[i] << endl;

// initialise all elements
cout << "*** Initialise all elements ***\n";
int* p3 = new int[3] {0};
for(int i = 0; i < 3; i++)
    cout << i << "\t" << p3[i] << endl;

//initialise all elements stack array
cout << "*** Initialise stack array ***\n";
int p4[3] = {0};
for(int i = 0; i < 3; i++)
    cout << i << "\t" << p4[i] << endl;

delete[] p1;
delete[] p2;
delete[] p3;
return 0;
}

这是输出:

*** Unitialised ***
0       6449456
1       0
2       3277144
*** Initialise individual elements ***
0       1
1       2
2       3
*** Initialise all elements ***
0       0
1       0
2       3277144
*** Initialise stack array ***
0       0
1       0
2       0

如果已在堆上分配了数组,则无法初始化所有元素,但如果已在堆栈上分配了数组,则可以这样做。 我的建议是,如果你坚持使用数组,那么使用你现有的代码,因为它是缓存友好的,几乎不需要任何时间来执行。 您可以找到一些有趣的答案herehere