Programming Tools/C++

[코드 중심 C++] - 멤버 이니셜라이저 컴파일 에러 문제 (Member Initializer)

LiDARian 2021. 5. 12. 22:17
반응형

knowledgeforengineers.tistory.com/75

 

[코드 중심 C++] - 상속, 멤버 이니셜라이저(Inheretence, Member Initializer)

1 클래스를 상속시키려면 상속받을 클래스의 이름 옆에 :와 접근 제한자, 클래스의 이름을 붙여주면 된다. 2 생성자 : 부모 먼저 자식 나중 소멸자 : 자식 먼저 부모 나중 3 멤버 이니셜라이저(

knowledgeforengineers.tistory.com

전에 올린 포스팅에 추가 설명을 하고자 한다.

 

Student 생성자를 아래와 같이 적었을 때 왜 컴파일 에러가 발생할까?

 

// Case1
Student(int studentID, string name){
	this->name = name;
	this->studentID = studentID;
}

// Case2
Student(int studentID, string name){
		Person(name);
		this->studentID = studentID;
}

// Case3
Student(int studentID, string name){
	this->studentID = studentID;
}

// Case4
Student(int studentID){
	this->studentID = studentID;
}

 


#include<iostream>
#include<string>

using namespace std;


class Person{
private:
	string name;
public:
	// Person(){ cout << "nothing" << endl;}
	Person(string name): name(name){}	//member initialization으로, 생성자의 몸체보다 먼저 실행된다.
	string getName(){
		return name;
	}
	void showName(){
		cout << "이름 : " << getName() << endl;
	}
};

int main(){
	Person person1;
	person1.showName();
	return 0;
}

// error: no matching function for call to ‘Person::Person()’
// 이렇게 생성자가 파라미터를 못받으면 기본 생성자가 생기는 게 아니라, 그냥 작동을 안한다.

기본 생성자 자체를 Person(string name)으로 해놓으면 파라미터를 받지 않는 Person() 생성자는 그냥 없는거다. 정 Person()과 Person(string name)생성자를 오버로딩해서 함께 쓰고자한다면 둘다 명시해야한다.

 

#include<iostream>
#include<string>

using namespace std;


class Person{
private:
	string name;
public:
	Person(){ cout << "nothing" << endl;}
	Person(string name): name(name){}	//member initialization으로, 생성자의 몸체보다 먼저 실행된다.
	string getName(){
		return name;
	}
	void showName(){
		cout << "이름 : " << getName() << endl;
	}
};

int main(){
	Person person1;
	person1.showName();
	return 0;
}

이렇게.

 


추가 설명을 하자면...

하위객체가 만들어지려면 우선 상위객체가 만들어져야한다. 그러므로 Student 생성자보다 먼저 실행되는 Member Initialization으로 상위객체의 생성자를 불러야한다. (putting 'Person(name)' in the constructor's body does not construct the superclass.)

그래서 아래와 같은 코드는 컴파일에러가 발생한다.

// Case2
Student(int studentID, string name){
		Person(name);
		this->studentID = studentID;
}

 


또한, 

Student(int studentID, string name){/**/}
//아래와 같다.
Student(int studentID, string name) : Person(), Temp() {/**/}

이런데... Person 클래스는 Person()생성자를 정의하지 않았으니 컴파일에러가 발생하게 된다.

 

 


하위클래스의 생성자를 선언할 때, 이렇게 선언하는 것을 권장한다.

Student(int studentID, string name) : Person(name), studentID(studentID) { }

참고

 

stackoverflow.com/questions/67489257/member-initialization-of-a-constructor-in-c?noredirect=1#comment119289090_67489257

 

www.google.com/search?q=google+translate&oq=google+tras&aqs=chrome.1.69i57j0i10l9.4655j0j7&sourceid=chrome&ie=UTF-8

반응형