정적 필드가 상속됩니까?
정적 멤버가 상속되면 전체 계층 구조 또는 해당 클래스에 대해 정적입니다. 즉 :
class SomeClass
{
public:
SomeClass(){total++;}
static int total;
};
class SomeDerivedClass: public SomeClass
{
public:
SomeDerivedClass(){total++;}
};
int main()
{
SomeClass A;
SomeClass B;
SomeDerivedClass C;
return 0;
}
세 가지 경우에 3 일 총 것, 또는 2 것 SomeClass
과 일을 SomeDerivedClass
?
3 모든 경우에 static int total
상속 된는 고유 변수가 아니라 SomeDerivedClass
에서 정확히 하나 SomeClass
이기 때문입니다.
편집 : @ejames가 그의 대답에서 발견하고 지적했듯이 모든 경우에 실제로 4 입니다.
편집 : 두 번째 질문의 코드는 int
두 경우 모두 누락 되었지만 추가하면 괜찮습니다.
class A
{
public:
static int MaxHP;
};
int A::MaxHP = 23;
class Cat: A
{
public:
static const int MaxHP = 100;
};
A :: MaxHP 및 Cat :: MaxHP에 대해 서로 다른 값을 사용하여 잘 작동합니다.이 경우 하위 클래스는 기본 클래스에서 정적을 "상속하지"않습니다. 하나.
의 구성으로 인해 합계가 두 번 증가하기 때문에 답은 실제로 모든 경우에 4 입니다 .SomeDerivedClass
다음은 완전한 프로그램입니다 (내 대답을 확인하는 데 사용) :
#include <iostream>
#include <string>
using namespace std;
class SomeClass
{
public:
SomeClass() {total++;}
static int total;
void Print(string n) { cout << n << ".total = " << total << endl; }
};
int SomeClass::total = 0;
class SomeDerivedClass: public SomeClass
{
public:
SomeDerivedClass() {total++;}
};
int main(int argc, char ** argv)
{
SomeClass A;
SomeClass B;
SomeDerivedClass C;
A.Print("A");
B.Print("B");
C.Print("C");
return 0;
}
결과 :
A.total = 4
B.total = 4
C.total = 4
파생 객체가 생성 될 때 파생 클래스 생성자가 기본 클래스 생성자를 호출하기 때문에 4입니다.
따라서 정적 변수의 값은 두 번 증가합니다.
#include<iostream>
using namespace std;
class A
{
public:
A(){total++; cout << "A() total = "<< total << endl;}
static int total;
};
int A::total = 0;
class B: public A
{
public:
B(){total++; cout << "B() total = " << total << endl;}
};
int main()
{
A a1;
A a2;
B b1;
return 0;
}
다음과 같습니다.
A() total = 1
A() total = 2
A() total = 3
B() total = 4
SomeClass () 생성자는 SomeDerivedClass ()가 호출 될 때 자동으로 호출됩니다. 이것은 C ++ 규칙입니다. 이것이 합계가 각 SomeClass 객체마다 한 번씩 증가한 다음 SomeDerivedClass 객체에 대해 두 번 증가하는 이유입니다. 2x1 + 2 = 4
세 가지 경우 모두 3입니다.
And for your other question, it looks like you really just need a const variable instead of static. It may be more self-explanatory to provider a virtual function that returns the variable you need which is overridden in derived classes.
Unless this code is called in a critical path where performance is necessary, always opt for the more intuitive code.
Yes, the derived class would contain the same static variable, i.e. - they would all contain 3 for total (assuming that total was initialized to 0 somewhere).
참고URL : https://stackoverflow.com/questions/998247/are-static-fields-inherited
'programing tip' 카테고리의 다른 글
Selenium-WebDriver에 Java에서 몇 초 동안 기다리도록 어떻게 요청할 수 있습니까? (0) | 2020.08.27 |
---|---|
Spring DAO 대 Spring ORM 대 Spring JDBC (0) | 2020.08.27 |
뾰족한 파일이 이동되면 Linux에서 열린 파일 핸들은 어떻게 되나요? (0) | 2020.08.27 |
C 표준 라이브러리 헤더 용 Eclipse CDT의 "해결되지 않은 포함"오류 (0) | 2020.08.27 |
PHP로 POST를 통해 다차원 배열 제출 (0) | 2020.08.27 |