Home > Back-end >  Turn to for help
Turn to for help

Time:09-17

The following code, this plan when calling foo function USES the parameter "student_teacher", but the current parameters as the "student", the compiler can still pass, please explain why, if you want to in this case, the compiler can prompt error, how to modify the class definition, and explain its reason,
#include
using namespace std;
The class CStudent
{
Public: CStudent () {}; ~ CStudent () {};
};
The class CTeacher
{
Public: CTeacher () {}; CTeacher CStudent (student) : m_student (student) {} ~ CTeacher () {}; Void called the () {cout<" The teacher "& lt; Private: CStudent m_student;
};
Void foo (CTeacher the teacher)
{the teacher called the ();
}
Int main ()
{CStudent student; CTeacher student_teacher; Foo (student);
}

CodePudding user response:

Because you have a copy constructor CTeacher, whose parameters are CStudent, means that you can directly through the CTeacher t=student copy out a CTeacher object (unless you override=), foo function calls the argument first copy to parameter, is equivalent to the CTeacher t=student, so the function can pass,

CodePudding user response:

reference 1st floor qybao response:
because you have a copy constructor CTeacher, whose parameters are CStudent, means that you can directly through the CTeacher t=student copy out a CTeacher object (unless you override=), foo function calls the argument first copy to parameter, is equivalent to the CTeacher t=student, so the function can pass,
what about the second question, please

CodePudding user response:

refer to the second floor qq_48608583 response:
Quote: refer to 1st floor qybao response:
because you have a copy constructor CTeacher, whose parameters are CStudent, means that you can directly through the CTeacher t=student copy out a CTeacher object (unless you override=), foo function calls the argument first copy to parameter, is equivalent to the CTeacher t=student, so the function can pass,
what about the second question, please
several kinds of modified methods, the copy constructor CTeacher are removed, or changing the parameters of the foo to the form of a pointer, or overloading=operator
  • Related