使用简单实例作为C遗产函数的参数
Using simple instance as parameter to a c legacy function
我为4*4矩阵定义了一个助手类:
class BCMatrix {
public:
float matrix[4][4];
void do_something_nice();
void do_something_else();
};
我有另一个来自C库的功能,无法被更改:
void copy_m4_m4(float r[4][4], float f[4][4]);
在我的bcmatrix类中,我可以做这样的事情:
float mat[4][4];
BCMatrix obmat;
copy_m4_m4(obmat.matrix, mat);
,但我实际上希望能够做这样的事情:
BCMatrix mat;
BCMatrix obmat;
copy_m4_m4(obmat, mat);
当然我可以添加一个操作员=或这样的简单函数:
void copy_m4_m4(BCMatrix &to, BCMatrix &from)
{
copy_m4_m4(t.matrix, f.matrix);
}
但我想知道是否有任何优雅(正确且令人愉快的(方式告诉编译器BCMATRIX实际上只是浮点[4] [4],以便使用一些额外的方法,因此可以直接将其用作参数copy_m4_m4((函数?
您需要一个隐式转换运算符,如以下内容。有关更多详细信息,请参见用户定义的转换。
class BCMatrix {
public:
using float_t = float[4]; // Typedef required because of array
operator float_t*() { return matrix; } // The conversion operator itself
float matrix[4][4];
void do_something_nice();
void do_something_else();
};
// Mock, to make sure it's working as planned
void copy_m4_m4(float r[4][4], float f[4][4]) {
for(auto i = 0; i < 4; ++i) {
for(auto j = 0; j < 4; ++j) {
std::cout << r[i][j] << ", ";
}
std::cout << std::endl;
}
}
int main() {
std::string testString = "testing";
// Test: fill the source array
BCMatrix obmat;
for(auto i = 0; i < 4; ++i) {
for(auto j = 0; j < 4; ++j) {
obmat[i][j] = 5 * i * j;
}
}
// Final step in proving it works: call the [4][4] function
BCMatrix mat;
copy_m4_m4(obmat, mat);
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 使用简单实例作为C遗产函数的参数
- 遗产.从父类调用子类函数