C ++ : 구조체가 클래스에서 상속 할 수 있습니까?
사용중인 API 구현을보고 있습니다.
구조체가 클래스에서 상속되고 있다는 것을 알았고 잠시 생각해 보았습니다.
첫째, 내가 공부 한 C ++ 매뉴얼에서 구조체가 다른 구조체에서 상속 할 수 있다는 것을 보지 못했습니다.
struct A {};
struct B : public A {};
그런 경우에 struct B는 stuct A의 모든 데이터를 상속받는다고 생각합니다. struct에서 public / private 멤버를 선언 할 수 있습니까?
그러나 나는 이것을 발견했습니다.
class A {};
struct B : public A {};
내 온라인 C ++ 설명서에서 :
클래스는 데이터 구조의 확장 된 개념입니다. 데이터 만 보유하는 대신 데이터 와 기능을 모두 보유 할 수 있습니다 .
클래스 A에 멤버 함수가 있어도 위의 상속이 유효합니까? 구조체가 상속하면 함수는 어떻게 되나요? 그리고 그 반대는 어떻습니까? 구조체로부터 상속받은 클래스?
실제로 말하면 다음과 같습니다.
struct user_messages {
std::list<std::string> messages;
};
그리고 저는 이것을 이렇게 반복했습니다 foreach message in user_messages.messages.
내 구조체에 멤버 함수를 추가하려면 선언을 변경하고 클래스로 "승격"하고 함수를 추가 한 다음 이전과 같이 user_messages.messages를 반복 할 수 있습니까?
분명히 나는 여전히 초보자이고 구조체와 클래스가 서로 어떻게 상호 작용하는지, 둘 사이의 실질적인 차이점은 무엇이며 상속 규칙이 무엇인지는 여전히 확실하지 않습니다.
예, 구조체는 C ++의 클래스에서 상속 할 수 있습니다.
C ++에서 클래스와 구조체는 상속 및 멤버의 액세스 수준과 관련된 기본 동작 을 제외하고는 동일 합니다.
C ++ 클래스
- 기본 상속 = 개인
- 멤버 변수 및 함수에 대한 기본 액세스 수준 = private
C ++ 구조체
- 기본 상속 = 공개
- 멤버 변수 및 함수에 대한 기본 액세스 수준 = public
C ++에서
struct A { /* some fields/methods ... */ };
다음과 같습니다.
class A { public: /* some fields/methods ... */ };
과
class A { /* some fields/methods ... */ };
다음과 같습니다.
struct A { private: /* some fields/methods ... */ };
즉, 구조체 / 클래스의 멤버는 기본적으로 public / private 입니다.
사용 struct또한 기본 상속 변경 에 public, 즉,
struct A { }; // or: class A { };
class B : A { };
다음과 같다
struct A { }; // or: class A { };
struct B : private A { };
그리고 반대로, 이것은
struct A { }; // or: class A { };
struct B : A { };
다음과 같습니다.
struct A { }; // or: class A { };
class B : public A { };
요약 : 예, struct은 클래스에서 상속 할 수 있습니다. class및 struct키워드 의 차이점 은 기본 개인 / 공용 지정자의 변경 일뿐입니다.
구조체와 클래스의 유일한 차이점은 멤버의 기본 액세스 수준입니다 (클래스의 경우 private, 구조체의 경우 public). 즉, 구조체는 클래스에서 상속 할 수 있어야하며 그 반대의 경우도 마찬가지입니다.
그러나 일반적으로 표준에서 요구하지 않는 구조체와 클래스가 사용되는 방식에는 차이가 있습니다. 구조체는 종종 순수한 데이터 (또는 프로젝트 선호도에 따라 다형성이없는 객체)에 사용되며 클래스는 다른 경우에 사용됩니다. 나는 이것이 단지 문체의 차이이며 필수가 아니라는 점을 강조합니다.
이해해야 할 가장 중요한 것은 구조체는 C에서 온 반면 클래스는 C ++라는 것입니다. 이것은 구조체가 일류 객체 지향 시민이지만 레거시 목적도 가지고 있음을 의미합니다. 이는 클래스가 분리되고 구조체가 기본 액세스 공용이되는 이유입니다. 그러나 일단 이것이 완료되면 완전히 완전히 동일하며 모든면에서 상호 교환이 가능합니다.
A struct is the same thing as a class except that a class defaults its members to private while a struct defaults its members to public. As a result, yes, you can inherit between the two. See in C++, can I derive a class from a struct.
struct and class are pretty much interchangeable - just with different defaults in that classes default to private inheritance and members, structs to public. The class keyword (and not struct) must be used for eg. "template <class T>".
That said, many programmers use the two to give a slight suggestion to a programmer reading the code: by using a struct you're subtly suggesting a less encapsulating, OO design. A struct might be used internal to a library - where getting at the guts of it all is fair game, whereas classes are used on the boundary where API changes would inconvenience clients and better abstraction is useful. This very loose convention has grown out of the difference in default accessibility - lazy/efficient/concise (take your pick) programmers do what's easiest unless there's a benefit otherwise, and not typing access specifiers is nice when possible.
Yes a struct can inherit from a class. struct and class differ only in the access-specifier assumed for the members and for a base classes (or structs) if not specified explicitly in C++ . For structs it's public. For classes it's private.
The sentence you quote from the manual is about the concept of a class in C++, as compared to the concept of a data structure in C. In C++ new keyword - class was introduced to better reflect the change in the concept, but for compatibility with code in C, an old keyword struct was left and it's meaning is as described above.
Yes. Struct can inherit from a class and vice versa. The accessibility rule is
$11.2/2- "In the absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class."
EDIT 2: So you can change your class as:. Note that it is a bad idea to have public data members usually.
class user_messages { // i also changed the name when OP was modified :)
public:
std::list<std::string> messages;
};
A class will not publicly inherit from a struct. A struct will publicly inherit from a class or a struct.
class A
{
public:
int a;
};
struct B : A
{};
B b; b.a=5; //OK. a is accessible
class A
{
public:
int a;
};
struct B : public A
{};
It means the same. B b; b.a=5; //OK. a is accessible
struct A
{int a;};
class B : A
{};
B b; b.a=5; //NOT OK. a is NOT accessible
struct A
{int a;};
class B : public A
{};
B b; b.a=5; //OK. a is accessible
Finally:
class A
{int a;};
class B : A
{};
B b; b.a=5; //NOT OK. a is NOT accessible
class A
{int a;};
class B : public A
{};
B b; b.a=5; //NOT OK. a is NOT accessible
참고URL : https://stackoverflow.com/questions/3574040/c-can-a-struct-inherit-from-a-class
'Nice programing' 카테고리의 다른 글
| 푸시 segue 대신 뷰 컨트롤러를 교체하거나 탐색 스택에서 제거하는 방법은 무엇입니까? (0) | 2020.11.19 |
|---|---|
| 상태를 속성에 바인딩하는 경우 [(ngModel)]과 [ngModel]의 차이점은 무엇입니까? (0) | 2020.11.19 |
| UITableView 바닥 글, 콘텐츠 위에 떠 다니는 것을 중지 (0) | 2020.11.19 |
| Java 프로젝트를 빌드하는 동안 IntelliJ IDEA에서 경고 메시지 제거 (0) | 2020.11.19 |
| 힘내 리베이스를 롤백하는 방법 (0) | 2020.11.19 |