I have struct:
struct mat4 {
开发者_如何学JAVAfloat m[16];
mat4();
...
float *getFloat();
}
float *mat4::getFloat() {
return m;
}
Now I want to make m equal to m from newly created matrix r:
void mat4::rotate(vec3 v) {
mat4 r, rx, ry, rz;
...
matrix calculations
...
m = *r.getFloat();
}
But this gives me error "incompatible types in assignment of ‘float’ to ‘float [16]’" I have searched Google and tried different ways but no success so far. Please tell me how could I do that?
getFloat()
returns a pointer. m
is an array. If you want to copy all of what is returned into m
you will need to use std::copy
or std::memcpy
:
std::memcpy(m, r.getFloat(), sizeof(m));
If you meant to get just one float from getFloat()
you could do:
m[0] = *r.getFloat();
r.getFloat()
is returning a pointer to a single float. This is dereferenced to give a single float, and then assigned to an array of 16 floats.
Assuming that m
contains the entire state of mat4
, you can use the built in assignment operator:
*this = r;
The compiler will automatically implement the struct dump/ memcpy to copy all 16 floats.
Don't use naked C arrays. This is C++, we can do a lot better:
#include <tr1/array> // or <array> if you're in MSVC or GCC
typedef std::tr1::array<float, 16> myfloats;
int main()
{
myfloats a, b;
a[0] = /* ... fill the array */
b = a; // done
}
You can also put the array into your matrix structure:
struct mat4
{
typedef std::tr1::array<float, 16> myfloats;
myfloats & data() { return m_data; }
mat4(); /* ... etc. ... */
private:
myfloats m_data;
};
You should be able to just assign variables of type mat4
to each other directly!
Use std::copy
as:
#include <algorithm>
std::copy(r.m, r.m+16, m);
Also, if you can use r.m
directly, why call r.getFloat()
then?
r.getFloat() returns a pointer to "its" m
. Arrays cannot be copied with simple assignment; you would have to work either with memcpy()
or memmove()
or with a for
loop over the array elements.
精彩评论