Development Tip

기본 클래스 생성자를 어떻게 호출합니까?

yourdevel 2020. 11. 23. 20:18
반응형

기본 클래스 생성자를 어떻게 호출합니까?


라 틀리 저는 자바로 많은 프로그래밍을했습니다. 당신은 당신이에서 상 속됨 클래스를이 전화 super();(모든 아마 알고)

이제 몇 가지 인수를 취하는 기본 생성자가있는 C ++ 클래스가 있습니다. 예:

class BaseClass {
public:
    BaseClass(char *name); .... 

클래스를 상속하면 적절한 기본 생성자가 없다는 경고가 표시됩니다. 그래서 super()C ++ 와 같은 것이 있습니까, 아니면 모든 변수를 초기화하는 함수를 정의해야합니까?


서브 클래스 생성자의 이니셜 라이저 목록에서이 작업을 수행합니다.

class Foo : public BaseClass {
public:
    Foo() : BaseClass("asdf") {}
};

인수를 사용하는 기본 클래스 생성자는 멤버가 초기화되기 전에 호출되어야합니다.


헤더 파일에서 기본 클래스를 정의하십시오.

class BaseClass {
public:
    BaseClass(params);
};

그런 다음 파생 클래스를 BaseClass 상속으로 정의합니다.

class DerivedClass : public BaseClass {
public:
    DerivedClass(params);
};

소스 파일에서 BaseClass 생성자를 정의하십시오.

BaseClass::BaseClass(params)
{
     //Perform BaseClass initialization
}

기본적으로 파생 생성자는 매개 변수없이 기본 기본 생성자 만 호출합니다. 따라서이 예제에서는 파생 생성자가 호출 될 때 기본 클래스 생성자가 자동으로 호출되지 않지만 콜론 ( :) 뒤에 기본 클래스 생성자 구문을 추가하면됩니다 . 기본 생성자를 자동으로 호출하는 파생 생성자를 정의합니다.

DerivedClass::DerivedClass(params) : BaseClass(params)
{
     //This occurs AFTER BaseClass(params) is called first and can
     //perform additional initialization for the derived class
}

BaseClass생성자는 먼저 호출되는 DerivedClass생성자, 동일한 / 다른 파라미터는 params원할 경우베이스 클래스로 전달 될 수있다. 더 깊은 파생 클래스에 대해 중첩 될 수 있습니다. 파생 생성자는 정확히 하나의 기본 생성자를 호출해야합니다. 소멸자는 생성자가 호출 된 역순으로 자동으로 호출됩니다.

편집 : virtual일반적으로 다중 상속 또는 다이아몬드 상속 을 달성하기 위해 클래스 에서 상속하는 경우이 규칙에 예외가 있습니다. 그런 다음 모든 virtual기본 클래스 의 기본 생성자를 명시 적으로 호출하고 매개 변수를 명시 적으로 전달해야합니다. 그렇지 않으면 매개 변수 없이 기본 생성자 만 호출합니다 . 참조 : 가상 상속-생성자 건너 뛰기


이니시 에이저를 사용해야합니다.

class DerivedClass : public BaseClass
{
public:
  DerivedClass()
    : BaseClass(<insert arguments here>)
  {
  }
};

이것은 또한 생성자가 없거나 초기화하려는 클래스의 멤버를 생성하는 방법입니다. 언급되지 않은 모든 멤버는 기본적으로 초기화됩니다. 예를 들면 :

class DerivedClass : public BaseClass
{
public:
  DerivedClass()
    : BaseClass(<insert arguments here>)
    , nc(<insert arguments here>)
    //di will be default initialized.
  {
  }

private:
  NeedsConstructor nc;
  CanBeDefaultInit di;
};

The order the members are specified in is irrelevant (though the constructors must come first), but the order that they will be constructed in is in declaration order. So nc will always be constructed before di.


Regarding the alternative to super; you'd in most cases use use the base class either in the initialization list of the derived class, or using the Base::someData syntax when you are doing work elsewhere and the derived class redefines data members.

struct Base
{
    Base(char* name) { }
    virtual ~Base();
    int d;
};

struct Derived : Base
{
    Derived() : Base("someString") { }
    int d;
    void foo() { d = Base::d; }
};

Use the name of the base class in an initializer-list. The initializer-list appears after the constructor signature before the method body and can be used to initialize base classes and members.

class Base
{
public:
  Base(char* name)
  {
     // ...
  }
};

class Derived : Base
{
public:
  Derived()
    : Base("hello")
  {
      // ...
  }
};

Or, a pattern used by some people is to define 'super' or 'base' yourself. Perhaps some of the people who favour this technique are Java developers who are moving to C++.

class Derived : Base
{
public:
  typedef Base super;
  Derived()
    : super("hello")
  {
      // ...
  }
};

There is no super() in C++. You have to call the Base Constructor explicitly by name.

참고URL : https://stackoverflow.com/questions/6923722/how-do-i-call-the-base-class-constructor

반응형