c++ - Can I convert a pointer to my class? -
i'm refactoring class project adapt int data. code quite complicated, try give simple example below:
struct { a(int a):a_(a) {} // supports implicit conversion int int a_; }; void print(a a) { cout<<a.a_<<endl; } void x2(a *a) { // change a's value a->a_ *= 2; } int main() { int b = 2; print(b); // pass int without problem x2(&b); // pass int* a* - failed cout<<b<<endl; // b supposed changed x2() }
in case maybe template choice, i'm afraid rewritting whole class template huge effort , little harm readablity colleagues.
is there other way use "int*" "a*"?
no, there's no "way". trying here violating contract on x2
, a
valid pointer a
.
the simplest change change x2
to: (there's no need use pointer here)
void x2 (a& a) { a.a_ *= 2; }
and call value that's wrapped around int (like @jrok suggested):
a a(2); x2(a);
if conderned printing, provide operator<<
a.
Comments
Post a Comment