class type conversion fails C++ -
i'm trying make compile, won't, , couldn't find relevant on web.
#include<iostream> using namespace std; class a; class b { int x; public: b(int i=107) {x=i;} operator a(); }; b::operator a() {return x;} class { int x; public: a(int i=6) {x=i;} int get_x() {return x;} }; int main() { a; b b=a; cout<<a.get_x(); return 0; }
i errors: return type 'class a' incomplete conversion 'a' non-scalar type 'b' requested
not works:
b b; a=b;
i don't know wrong, , don't know find more info on subject.
thank you
you didn't post full text of errors, means left out important line numbers. case, line numbers valuable piece of information in error.
class a; class b { ... }; b::operator a() {return x;}
i'm guessing line compiler telling error occurs on.
at line of code, compiler not yet have complete declaration of a
has no idea how convert int x
class a
. c++ compilation single pass, can't defer lookup.
you need complete declarations before proceed definitions.
class a; class b { int x; public: b(int i=107) {x=i;} operator a(); }; class { int x; public: a(int i=6) {x=i;} int get_x() {return x;} }; // done declarations. begin definitions. b::operator a() {return x;} // compiler quietly expands be: // b::operator a() { return a::a(i=this->x); }
typically a
, b
in header files , keep definition, requires both classes declared, .cpp file somewhere.
Comments
Post a Comment