C ++의 추상 클래스 대 인터페이스
중복 가능성 :
C ++에서 인터페이스를 어떻게 선언합니까?
이것은 C ++에 대한 일반적인 질문입니다. 아시다시피, 구별이 명확하지 interface
및 abstract class
자바와 C #과 달리 C ++에서이. C ++에서 를 사용하는 interface
것이 언제 더 선호 abstract class
됩니까? 몇 가지 예를 들어 주시겠습니까?
인터페이스 에서는 순수 가상 메서드 (즉, 코드 없음) 만있는 C ++ 클래스를 의미 한다고 가정합니다 . 대신 추상 클래스 에서는 재정의 할 수있는 가상 메서드와 일부 코드가 포함 된 C ++ 클래스를 의미하지만 하나 이상의 순수 가상 메서드를 의미합니다. 클래스를 인스턴스화 할 수 없습니다. 예 :
class MyInterface
{
public:
// Empty virtual destructor for proper cleanup
virtual ~MyInterface() {}
virtual void Method1() = 0;
virtual void Method2() = 0;
};
class MyAbstractClass
{
public:
virtual ~MyAbstractClass();
virtual void Method1();
virtual void Method2();
void Method3();
virtual void Method4() = 0; // make MyAbstractClass not instantiable
};
Windows 프로그래밍에서 인터페이스 는 COM의 기본입니다 . 실제로 COM 구성 요소는 인터페이스 (예 : v-tables 에 대한 포인터, 즉 함수 포인터 집합에 대한 포인터) 만 내 보냅니다 . 이는 예를 들어 C ++로 COM 구성 요소를 빌드하고 Visual Basic에서 사용하거나, C로 COM 구성 요소를 빌드하고 C ++에서 사용하거나, Visual C ++로 COM 구성 요소를 빌드 할 수 있도록하는 ABI (Application Binary Interface)를 정의하는 데 도움이됩니다. 버전 X를 사용하고 Visual C ++ 버전 Y와 함께 사용합니다. 즉, 인터페이스를 사용하면 클라이언트 코드와 서버 코드 간의 분리가 높습니다.
또한 이 기사 에서 설명한대로 C ++ 객체 지향 인터페이스 (순수 C DLL 대신)를 사용하여 DLL을 빌드하려는 경우 C ++ 클래스 대신 인터페이스 ( "성숙한 접근 방식") 를 내보내는 것이 좋습니다. COM은 수행하지만 COM 인프라의 부담이 없습니다.
구체적인 특정 동작을 지정하지 않고 구성 요소를 프로그래밍 할 수있는 규칙 집합을 정의 하려면 인터페이스를 사용합니다 . 이 인터페이스를 구현하는 클래스는 자체적으로 구체적인 동작을 제공합니다.
대신에, 나는 사용하십시오 추상 클래스를 좀 기본 제공하려는 경우 인프라 코드 와 동작을하고, 클라이언트 코드로 가능하게 도출이 추상 클래스에서, 일부 사용자 지정 코드를 사용하여 순수 가상 메소드를 오버라이드 (override), 및 완료 와 함께이 동작을 맞춤 코드. OpenGL 애플리케이션의 인프라를 예로 들어 보겠습니다. OpenGL을 초기화하고 창 환경을 설정하는 등의 추상 클래스를 정의한 다음이 클래스에서 파생하여 렌더링 프로세스 및 사용자 입력 처리를위한 사용자 정의 코드를 구현할 수 있습니다.
// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL;
// client code must derive from it
// and implement rendering and user input.
class OpenGLApp
{
public:
OpenGLApp();
virtual ~OpenGLApp();
...
// Run the app
void Run();
// <---- This behavior must be implemented by the client ---->
// Rendering
virtual void Render() = 0;
// Handle user input
// (returns false to quit, true to continue looping)
virtual bool HandleInput() = 0;
// <--------------------------------------------------------->
private:
//
// Some infrastructure code
//
...
void CreateRenderingWindow();
void CreateOpenGLContext();
void SwapBuffers();
};
class MyOpenGLDemo : public OpenGLApp
{
public:
MyOpenGLDemo();
virtual ~MyOpenGLDemo();
// Rendering
virtual void Render(); // implements rendering code
// Handle user input
virtual bool HandleInput(); // implements user input handling
// ... some other stuff
};
interface
주로 Java에서 인기를 얻었습니다.
다음은의 특성 interface
과 해당 C ++에 해당하는 것입니다.
interface
can contain only body-less abstract methods; C++ equivalent is purevirtual
methods, though they can/cannot have bodyinterface
can contain onlystatic final
data members; C++ equivalent isstatic const
data members which are compile time constants- Multiple
interface
can beimplement
ed by a Javaclass
, this facility is needed because a Javaclass
can inherit only 1class
; C++ supports multiple inheritance straight away with help ofvirtual
keyword when needed
Because of point 3 interface
concept was never formally introduced in C++. Still one can have a flexibility to do that.
Besides this you can refer Bjarne's FAQ on this topic.
An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).
Pure Virtual Functions are mostly used to define:
a) abstract classes
These are base classes where you have to derive from them and then implement the pure virtual functions.
b) interfaces
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.
Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.
class IInterface()
{
Public:
Virtual ~IInterface(){};
…
}
Class ClassImpl : public IInterface
{
…
}
Int main()
{
IInterface* pInterface = new ClassImpl();
…
delete pInterface; // Wrong in OO Programming, correct in C++.
}
참고URL : https://stackoverflow.com/questions/12854778/abstract-class-vs-interface-in-c
'program tip' 카테고리의 다른 글
업로드하기 전에 파일 크기, 이미지 너비 및 높이 가져 오기 (0) | 2020.09.01 |
---|---|
MongoDB의 인덱스 목록? (0) | 2020.09.01 |
목록 항목 사이의 세로 간격을 어떻게 설정합니까? (0) | 2020.09.01 |
Lambda 란 무엇입니까? (0) | 2020.09.01 |
Unix에서 다른 프로세스의 환경 변수를 변경하는 방법이 있습니까? (0) | 2020.09.01 |