将类互换使用浮动指针

Use class as a float pointer interchangeably

本文关键字:指针 互换      更新时间:2023-10-16

我想知道它是否存在一种互换使用类和浮动指针的方法。假设课程基本上是双打(固定尺寸)的数组。如果我有类指针,我可以将其用作浮动指针(与适当的操作员一起使用),但是,如果我有指针,我不知道如何自动将其用作类。

让我再解释一下我的问题。我一直在使用Matrix4x4 Typedef保存4x4矩阵:

typedef float Matrix4x4[16];

我有很多功能将Matrix4x4作为float*现在,我正在尝试以使用Matrix4x4的方式使用基本类:

class Matrix4x4 {
    float matrix[16];
public:
    Matrix4x4();
    float operator[](int i){
        return matrix[i];
    }
    operator float*() const{ // I can pass to functions that take a float*
        return (float*) matrix;
    }
};

当我需要调用这样的函数时,问题仍然存在:

bool test(void){
    float H[16];
    // ... process H
    return isIdentidy(         H); // I want the compiler to accept it this way
    return isIdentidy((float*) H); // or this way
}
bool isIdentity(const Matrix4x4 matrix){
    ... (process)
    return ...;
}

在最后,指针应该是相同的吧?

(如果我将h声明为 Matrix4x4 H,而不是 float H[16]

有没有办法无需使用static_cast或dynamic_cast?

非常感谢

没有办法做你想做的事,但是你可以做一些非常相似的事情。

首先为接受float [16]参数

的Matrix4x4制作新的构造函数
class Matrix4x4 {
    float matrix[16];
public:
    Matrix4x4();
    Matrix4x4(float values[16])
    {
        memcpy(matrix, values, sizeof(float)*16);
    }
    float operator[](int i){
        return matrix[i];
    }
    operator float*() const{
        return (float*) matrix;
    }
};

然后您可以做

bool test(void){
    float H[16];
    // ... process H
    return isIdentidy(Matrix4x4(H));
}
bool isIdentity(const Matrix4x4 matrix){
    ... (process)
    return ...;
}

新Matrix4x4的任何更改都将丢失。