c++ - Constructor can only be defined outside class -
in following code, constructor can defined outside class, or compiler give errors.
class student; class teacher { private: int num; string name; string sex; string title; public: teacher(student &s) { num=s.num ; name=s.name ; sex=s.sex ; } void display(); }; class student { public: int num; string name; string sex; float grade; friend teacher; void set_student(); }; void teacher::display() { cout<<num<<" "<<name<<" "<<sex<<endl; } void student::set_student() { cin>>num>>name>>sex>>grade; } int main() { student s1; s1.set_student() ; teacher t1(s1); t1.display() ; return 0; }
it didn't compile, if move definition of constructor outside class, compiles:
class teacher { public: teacher(student &s); ... }; teacher::teacher(student &s) { num=s.num ; name=s.name ; sex=s.sex ; }
the error is:
floyd.cpp: in constructor 'teacher::teacher(student&)': floyd.cpp:37:8: error: invalid use of incomplete type 'class student' num=s.num ; ^ floyd.cpp:27:7: error: forward declaration of 'class student' class student; ^ floyd.cpp:38:9: error: invalid use of incomplete type 'class student' name=s.name ; ^ floyd.cpp:27:7: error: forward declaration of 'class student' class student; ^ floyd.cpp:39:8: error: invalid use of incomplete type 'class student' sex=s.sex ; ^ floyd.cpp:27:7: error: forward declaration of 'class student' class student;
why happen?
in order able compile declaration
teacher(student &s);
the compiler needs know class student
exists. forward declaration
class student;
successfully fulfills requirement: tells compiler there going definition of class student
@ later point. however, in order able compile code
teacher(student &s) { num=s.num ; ... }
the compiler needs know content of student
class well. specifically, needs know student
has member variable num
. not possible until point of program student
class defined.
there 2 ways of addressing issue:
- you discovered first 1 - move constructor definition out of class, or
- switch order of declarations, , forward-declare
teacher
- possible becausestudent
's code not depend onteacher
's definition.
Comments
Post a Comment