-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
해결됨
생성자 호출 관련 질문
22.01.03 21:56 작성 조회수 99
1
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Teacher {
std::string m_name;
public:
Teacher(const std::string& name_input = "No name")
: m_name(name_input) {
std::cout << "Teacher" << std::endl;
}
~Teacher() {}
void setName(const std::string& name_in) {
m_name = name_in;
}
std::string getName() {
return m_name;
}
friend std::ostream& operator<<(std::ostream& os, const Teacher& teacher) {
os << teacher.m_name << std::endl;
return os;
}
};
class Student {
std::string m_name;
int m_intel;
public:
Student(const std::string& name_in = "No name", const int& intel_in = 0)
: m_name(name_in)
, m_intel(intel_in) {
std::cout << "Student" << std::endl;
}
~Student() {}
void setName(const std::string& name_in) {
m_name = name_in;
}
void setIntel(const int& intel_in) {
m_intel = intel_in;
}
int getIntel() {
return m_intel;
}
friend std::ostream& operator<<(std::ostream& os, const Student& student) {
os << student.m_name << " " << student.m_intel;
return os;
}
};
class Lecture {
std::string m_name;
Teacher m_teacher;
std::vector<Student> m_students;
public:
Lecture(const std::string& name_in = "No Name")
: m_name(name_in) {
std::cout << "Lecture" << std::endl;
}
~Lecture() {
//do Not delete teacher, students
}
void assignTeacher(const Teacher& teacher) {
m_teacher = teacher;
}
void registerStudent(const Student& const student) {
m_students.push_back(student);
}
void study() {
std::cout << m_name << " Study " << std::endl << std::endl;
for (auto& element : m_students)
element.setIntel(element.getIntel() + 1);
}
friend std::ostream& operator<<(std::ostream& os, const Lecture& lecture) {
os << "Lecture name : " << lecture.m_name << std::endl;
os << lecture.m_teacher;
for (auto& element : lecture.m_students)
os << element << std::endl;
return os;
}
};
int main() {
using namespace std;
Lecture lec1("Introduction to Computer Programming");
lec1.assignTeacher(Teacher("Prof. Hong"));
lec1.registerStudent(Student("A", 1));
lec1.registerStudent(Student("B", 2));
lec1.registerStudent(Student("C", 3));
Lecture lec2("Computational Thinking");
lec2.assignTeacher(Teacher("Prof. Good"));
lec2.registerStudent(Student("A", 0));
//TODO. implement Aggregation Relationship
//test
{
cout << lec1 << endl;
cout << lec2 << endl;
lec2.study();
cout << lec1 << endl;
cout << lec2 << endl;
}
}
Lecture를 생성하면 Teacher도 같이 생성됩니다
그런데 Lecture 생성자 안에 Teacher와 관련된건 없을텐데 생성되니깐 궁금해서 질문합니다
답변을 작성해보세요.
2
홍정모
지식공유자2022.01.04
티쳐가 렉쳐의 멤버로 있습니다. 이때는 생성자 호출을 해주지 않더라도 생성이 되어야 하기 때문에 가장 기본이 되는 생성자를 호출합니다. 만약에 티쳐의 기본 생성자를 막아 버렸다면 (아마 생성자 부분에서 나왔을겁니다.) 티쳐를 생성 못해서 렉쳐도 생성을 할 수 없는 상황이 되어서 오류가 발생합니다.
답변 1