在构造函数中分配数组

时间:2015-02-06 19:24:39

标签: c++

在课堂上 我有一个公共属性TissueCompartments:

class Diver {
public:
    TissueCompartments tissueCompartments[16];
    Diver();
    Diver(const Diver& orig, TissueCompartments tissueCompartments[16]);
    virtual ~Diver();
};

我有一个构造函数

Diver::Diver(const Diver& orig, TissueCompartments tissueCompartments[16]) {
    this->tissueCompartments=tissueCompartments;
}

我收到此错误:  错误:'TissueCompartments *'与'TissueCompartments [16]'分配不兼容的类型

4 个答案:

答案 0 :(得分:5)

数组不可分配。在构造函数体中执行此操作:

#include <algorithm>
//..
Diver::Diver(const Diver& orig, TissueCompartments* tC)
{
    std::copy(tC, tC + 16, tissueCompartments);
    //...
}

此外,请注意此声明:

Diver::Diver(const Diver& orig, TissueCompartments tissueCompartments[16]) 

与此无异:

Diver::Diver(const Diver& orig, TissueCompartments* tissueCompartments)

即使您在参数中放置[16],数组也会衰减为指针。所以[16]绝对没有效果(除了帮助你知道它是一个16的数组)。

请注意,在进行任何这些更改之前,TissueCompartment类型必须是可分配的类型。

答案 1 :(得分:1)

无法分配数组。让人们兴奋的另一件事是,函数不能通过值来获取数组 - 编译器implicitly decays array arguments to pointers。如果您想要一个具有值语义的数组,请使用std::array

class Diver {
public:
    std::array<TissueCompartments, 16> tissueCompartments;
    Diver();
    Diver(const Diver& orig, std::array<TissueCompartments, 16> tissueCompartments);
    virtual ~Diver();
};

Diver::Diver(const Diver& orig, std::array<TissueCompartments, 16> tissueCompartments) {
    this->tissueCompartments=tissueCompartments;
}

答案 2 :(得分:1)

虽然数组不可分配,但您可以使用大括号初始化程序轻松绕过示例中的限制。
由于建设性的懒惰,我使用了构造函数委派和std::index_sequence

#include <utility>

template<size_t... i> Diver::Diver<i...>(const Diver& orig,
        TissueCompartments tissueCompartments, std::index_sequence<i...>)
    : tissueCompartments{tissueCompartments[i]...}
{}

Diver::Diver(const Diver& orig, TissueCompartments tissueCompartments[16])
    : Diver(orig, tissueCompartments, std::make_index_sequence(16) {}

帮助程序是C ++ 14,但只使用C ++ 11功能。

答案 3 :(得分:0)

与涉及数组的任何问题一样,您首先想到的是停止使用数组,而是使用vector

#include <vector>
class Diver {
public:
    std::vector<TissueCompartments> tissueCompartments;
    Diver();
    Diver(const Diver& orig, std::vector<TissueCompartments> tissueCompartments);
    virtual ~Diver();
};

然后你可以这样做:

Diver::Diver(const Diver& orig, std::vector<TissueCompartments> tissueCompartments) {
    this->tissueCompartments=tissueCompartments;
}

并且,如果您正在使用C ++ 11,您应该能够构建一个带有初始化列表的Diver,假设Diver是由int和字符串构造的:

Diver d{ {1,"hi"}, {2,"hi"}, {3,"hi"}, {4,"hi"}
       , {5,"hi"}, {6,"hi"}, {7,"hi"}, {8,"hi"}
       , {9,"hi"}, {10,"hi"}, {11,"hi"}, {12,"hi"}
       , {13,"hi"}, {14,"hi"}, {15,"hi"}, {16,"hi"}
       };