c++ - 交替使用类作为浮点指针

标签 c++ arrays class pointers

我想知道是否存在一种可以互换使用类和浮点指针的方法。可以说一个类基本上是一个 double 组(固定大小)。如果我有类指针,我可以将它用作浮点指针(使用适当的运算符很容易),但是,如果我有指针,我不知道如何自动将它用作类。

让我再解释一下我的问题。 我一直在使用 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 的任何更改都将丢失。

关于c++ - 交替使用类作为浮点指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21443640/

相关文章:

c++ - snprintf 与 std::stringstream

c# - 以大写形式显示句子中的最后一个单词

javascript - 迭代数组以使用样式元素的数据属性,但仅获取数组中的最后一个值

python - x=x[class_id] 在 NumPy 数组上使用时会做什么

c++ - Boost 序列化 text_iarchive 进程终止

C++ 返回类型重载技巧

c++ - 为什么 Boost.Range is_sorted 不需要前向迭代器?

Java - 父类(super class)(继承)与父类(无继承)

javascript - 从类找到的元素中获取元素类型

c++ 类继承,未定义对 'Class::Constructor()' 的引用