简体   繁体   English

c++ 中运算符的固定大小数组

[英]fixed-size array for operators in c++

I've been this trying for several hours now.我已经尝试了几个小时了。 I cannot find a way to pass a fixed-size array to an operator.我找不到将固定大小的数组传递给运算符的方法。 I found some stuff here on stackoverflow and tried it that way, as you can see in my code, but it won't work at all.正如您在我的代码中看到的那样,我在 stackoverflow 上找到了一些东西并尝试了这种方式,但它根本不起作用。 The task is, that the code shouldn't be compiled if the array is not of size 3, that means, that if the array is of size 2 or size 4, that I should get a compile error.任务是,如果数组的大小不是 3,则不应编译代码,这意味着,如果数组的大小为 2 或 4,我应该得到一个编译错误。 Can someone tell me how to implement this?有人可以告诉我如何实现吗? Thanks in advance: :)提前致谢: :)

class Vec3 {
private:
int x, y, z;
public:
Vec3 (int x, int y, int z) : x(x), y(y), z(z) {}
int getX () const
{
    return x;
}
int getY () const
{
    return y;
}
int getZ () const
{
    return z;
}
};

Vec3 operator+(Vec3 &vec, int (*arr)[3]) {
int x,y,z;
x = vec.getX() + (*arr)[0];
y = vec.getY() + (*arr)[1];
z = vec.getZ() + (*arr)[2];
Vec3 result(x,y,z);
return result;
}

int main () {
Vec3 v1 (1,2,3);
int  v3 [] = {2,4,6};

cout << "v1 + v3 = " << v1 + v3 << endl;

return 0;
}

You got the syntax slightly wrong.您的语法略有错误。 Instead of代替

Vec3 operator+(Vec3 &vec, int (*arr)[3])

it must be肯定是

Vec3 operator+(Vec3 &vec, int (&arr)[3])

to pass the array by reference.通过引用传递数组。 And you can drop the value-of-operator ( * ) before the array-access, so you end up with您可以在数组访问之前删除操作符的值( * ),因此您最终得到

Vec3 operator+(Vec3 &vec, int (&arr)[3]) {
    int x,y,z;
    x = vec.getX() + arr[0];
    y = vec.getY() + arr[1];
    z = vec.getZ() + arr[2];

    Vec3 result(x,y,z);

    return result;
}

Use template to do it:使用模板来做到这一点:

template<size_t N>
Vec3 operator+(Vec3 &vec, int (&arr)[N]) {
    static_assert(N==3,"wrong size of array");
    // the rest of the code , small fix: arr[0] etc 

static assert will be triggered when N is not equal to 3.当 N 不等于 3 时,将触发 static 断言。

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM