【问题标题】:Unable to initialize a 2d Vector in my C++ class无法在我的 C++ 类中初始化二维向量
【发布时间】:2016-05-22 04:51:21
【问题描述】:

我已经阅读了我能找到的关于这个主题的所有帖子,但无法弄清楚我做错了什么。我无法成功初始化我的类的成员变量 2d 向量。头文件是:

class Beam2
    {
    private:
        /*The following unit vectors should never be accessed directly
        and are therefore private.*/
        std::vector<std::vector<double> > unitVectors;

    public:
    //constructor
    Beam2(
        Node * node1PtrInput, Node * node2PtrInput,
        double orientAngleInput);

我的 cpp 文件

Beam2::Beam2(
Node * node1PtrInput, Node * node2PtrInput, double orientAngleInput){
node1Ptr = node1PtrInput;
node2Ptr = node2PtrInput;
orientAngle = orientAngleInput;
unitVectors(3, std::vector<double>(3));
updateUnitVectors();

错误是:错误:不匹配调用'(std::vector >) (int, std::vector)' unitVectors(3, std::vector(3)); ^ 任何帮助,将不胜感激。

【问题讨论】:

    标签: c++ multidimensional-array vector


    【解决方案1】:

    这是初始化类的正确方法:

    Beam2::Beam2(Node * node1PtrInput, Node * node2PtrInput, double orientAngleInput) :
    node1Ptr(node1PtrInput),
    node2Ptr(node2PtrInput),
    orientAngle(orientAngleInput),
    unitVectors(3, std::vector<double>(3))
    {
        updateUnitVectors(); // I believe this is function in the class
    }
    

    您也可以通过将 unitVectors(3, std::vector&lt;double&gt;(3)); 替换为 unitVectors.resize(3, std::vector&lt;double&gt;(3)); 来修复您的代码,但更喜欢前者。

    【讨论】:

    • 感谢您的回复。那么为什么会抛出错误呢?我认为,虽然语法不同,但语句是等价的。
    • 当你进入body构造函数时,unitVectors已经被初始化为默认值。所以,你不能像unitVectors(3, std::vector&lt;double&gt;(3)); 那样再次初始化它,你必须调整它的大小。
    猜你喜欢
    • 2013-11-04
    • 2021-10-02
    • 2015-07-20
    • 1970-01-01
    • 2018-06-26
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多