C++의 객체 슬라이싱

Jinku Hu 2023년10월12일
C++의 객체 슬라이싱

이 기사에서는 C++에서 객체 슬라이싱을 소개합니다.

C++의 기본 클래스에 대한 파생 클래스 개체에 개체 분할 사용

객체 지향 프로그래밍의 핵심 개념은 상속이며, 이는 클래스가 서로 관련되고 계층을 형성 할 수 있음을 의미합니다. 계층 구조의 루트는 일반적으로 다른 클래스가 데이터 멤버 또는 함수의 형태로 기능을 상속하는 기본 클래스라고합니다. 다른 클래스에서 상속하는 클래스를 파생 클래스라고합니다. 기본 클래스 멤버에 대한 액세스 제어와 파생 클래스에서 액세스 할 수있는 멤버를 지정하는 여러 유형의 상속이 있습니다. 예를 들어 기본 클래스의 전용 멤버는 파생 클래스에서 직접 액세스 할 수 없습니다. 대신 파생 클래스는public메서드를 사용하여 이러한 멤버를 검색해야합니다. 기본 클래스는 파생 클래스에서 직접 액세스 할 수있는protected식별자를 사용하여 별도의 멤버 집합을 지정할 수 있습니다.

이 경우 파생에서 기본으로의 변환 규칙과 이러한 기능에 대한 사용 사례에 중점을 둡니다. 일반적으로 파생 클래스에는 파생 클래스 자체에 정의 된 비 정적 멤버와 다른 클래스에서 상속 된 모든 멤버가 포함됩니다. 파생 개체가 기본 클래스 개체에 할당되면 할당 연산자 실행은 기본 클래스에서 가져옵니다. 따라서이 연산자는 기본 클래스 멤버에 대해서만 알고 있으며 할당 작업 중에 해당 멤버 만 복사됩니다.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::string;

class Person {
 protected:
  string name;

 public:
  explicit Person(string s) : name(std::move(s)) {}

  string getName() { return name; };
};

class Athlete : public Person {
  string sport;

 public:
  explicit Athlete(string s) : Person(std::move(s)){};
  Athlete(string s, string sp) : Person(std::move(s)), sport(std::move(sp)){};

  string getSport() { return sport; }
};

class Politician : public Person {
  string party;

 public:
  explicit Politician(string s) : Person(std::move(s)) {}
  Politician(string s, string p) : Person(std::move(s)), party(std::move(p)) {}

  string getParty() { return party; }
};

int main() {
  Politician p1("Lua", "D");
  Athlete a1("Lebron", "LA Lakers");

  cout << p1.getName() << " " << p1.getParty() << endl;

  Person p0 = p1;
  Athlete a2(p0.getName());

  cout << p0.getName() << endl;
  cout << a2.getName() << endl;

  return EXIT_SUCCESS;
}

출력:

Lua D
Lua

이전 예제 코드는Person클래스에서 파생 된PoliticianAthlete의 두 클래스를 정의합니다. 따라서Politician개체를Person에 할당 할 수 있지만 다른 방법으로는 할당 할 수 없습니다. 할당이 완료되면 새로 만든p0개체에서 멤버 함수getParty에 액세스 할 수 없습니다. 결과적으로 다음 버전의 코드는p0Politician클래스의 멤버를 호출하므로 컴파일 타임 오류가 발생합니다.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::string;

class Person {
 protected:
  string name;

 public:
  explicit Person(string s) : name(std::move(s)) {}

  string getName() { return name; };
};

class Athlete : public Person {
  string sport;

 public:
  explicit Athlete(string s) : Person(std::move(s)){};
  Athlete(string s, string sp) : Person(std::move(s)), sport(std::move(sp)){};

  string getSport() { return sport; }
};

class Politician : public Person {
  string party;

 public:
  explicit Politician(string s) : Person(std::move(s)) {}
  Politician(string s, string p) : Person(std::move(s)), party(std::move(p)) {}

  string getParty() { return party; }
};

int main() {
  Politician p1("Lua", "D");
  Athlete a1("Lebron", "LA Lakers");

  cout << p1.getName() << " " << p1.getParty() << endl;

  Person p0 = p1;
  Politician p2 = p0;
  Politician p2 = a1;

  cout << p0.getName() << " " << p0.getParty() << endl;

  return EXIT_SUCCESS;
}
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - C++ Class