繁体   English   中英

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

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

我已经尝试了几个小时了。 我找不到将固定大小的数组传递给运算符的方法。 正如您在我的代码中看到的那样,我在 stackoverflow 上找到了一些东西并尝试了这种方式,但它根本不起作用。 任务是,如果数组的大小不是 3,则不应编译代码,这意味着,如果数组的大小为 2 或 4,我应该得到一个编译错误。 有人可以告诉我如何实现吗? 提前致谢: :)

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;
}

您的语法略有错误。 代替

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

肯定是

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

通过引用传递数组。 您可以在数组访问之前删除操作符的值( * ),因此您最终得到

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;
}

使用模板来做到这一点:

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 

当 N 不等于 3 时,将触发 static 断言。

演示

暂无
暂无

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

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