"부모"클래스를 만들려고합니다. 공용 생성자와 매개 변수 유형을 모두 상속 된 클래스에 제공합니다. 상속 된 것 사이에서 변경되는 유일한 것은 정적 변수의 값입니다.상속 된 클래스에서 정적 변수를 초기화하는 방법은 무엇입니까?
이 작업을 수행하는 가장 좋은 방법은 무엇입니까?
class Ball {
public:
virtual ~Ball();
Ball();
protected:
static string file;
static int size;
node shape;
};
class TenisBall: public Ball {};
class OtherBall: public Ball {};
Ball::Ball() {
shape = // do something with file and size
};
Ball::~Ball() {
delete shape;
};
string TenisBall::file = "SomeFile";
int TenisBall::size = 20;
string OtherBall::file = "OtherFile";
int OtherBall::size = 16;
내 문제는 다음과 같습니다 : 이것은 내 현재 시도 내가 코드의 마지막 두 줄 Ball
에 대한 TenisBall
및 OtherBall
을 변경하면 나는 TenisBall
및 OtherBall
클래스의 정적 값을 설정할 수 없습니다, 컴파일러는 받아들입니다. 어떻게해야합니까? 이것이 최선의 접근 방법입니까?
편집 :
는 제공된 답변에 따라, 나는 가상 함수를 사용하여 구현을 시도하기로 결정했다.
class Ball {
public:
Ball() {
shape = // do something with getSize and getFile
};
~Ball() {
delete shape;
};
protected:
virtual string getFile(){ return "Fake"; };
virtual int getSize(){ return 10; };
node shape;
};
class TenisBall: public Ball {
int getSize() { return 16; };
string getFile() { return "TennisBall.jpg"; };
};
int main() {
TenisBall ball;
return 1;
};
하지만 내 편집기 (엑스 코드)이 오류를 제공하지 않는 동안 컴파일하려고 할 때, LLVM은 다음과 같은 오류 제공 : 여기 내 코드는 지금까지입니다
invalid character '_' in Bundle Identifier at column 22. This string must be a uniform type identifier (UTI) that contains only alphanumeric (A-Z,a-z,0-9), hyphen (-), and period (.) characters.
IMO 여기에 올바른 디자인에서 정적 멤버를 사용하지 않는 것입니다 모두 (같은 크기의 모든 공은 모두 똑같은 것으로 보입니까?) 의심 스럽습니다. – stijn
관련 항목 : http://stackoverflow.com/questions/998247/are-static-members-inherited-c - static members don ' 네가 상속 재산처럼 행동하지 마라. – Mat
기본 클래스는 정적 변수를 파생 클래스와 공유합니다. 파생 클래스에서 초기화하는 것은 의미가 없습니다. –