如何使用数组作为参数创建构造函数?

时间:2019-04-22 09:57:29

标签: c++ arrays constructor

我有Wektor类和带有一,三和四个参数的构造函数。我还需要一个浮点数组作为参数,但不知道如何创建

Wektor(){
        this -> x = 0;
        this -> y = 0;
        this -> z = 0;
        this -> w = 0;
    }

    Wektor(float x){
        this -> x = x;
    }

Wektor(float x, float y, float z) {
        this -> x = x;
        this -> y = y;
        this -> z = z;
    }

    Wektor(float x, float y, float z, float w) {
        this -> x = x;
        this -> y = y;
        this -> z = z;
        this -> w = w;
    }

1 个答案:

答案 0 :(得分:0)

为c数组创建构造函数

C数组不能通过副本传递,但是它们可以通过引用传递。有两种方法可以做到这一点。

第一种方式:

using four_floats = float[4]; 

Wektor(four_floats const& arr) {
    x = arr[0];
    y = arr[1];
    z = arr[2];
    w = arr[3]; 
}

第二种方法。。这种方法使用的是邪恶的,卑鄙的语法,实际上很难看。

Wektor(float const (&arr)[4]) {
    x = arr[0];
    y = arr[1];
    z = arr[2];
    w = arr[3]; 
}

std::array创建构造函数

这很简单。

Wector(std::array<float, 4> const& arr) {
    x = arr[0];
    y = arr[1];
    z = arr[2];
    w = arr[3];
}
相关问题