简体   繁体   中英

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. 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. 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.

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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