템플릿 기반 클래스가 있습니다 템플릿이 아닌 템플릿 부모 인을 상속받은 자식입니다. 자식 헤더를 여러 .cpp 파일에 포함하면 LNK2005 오류가 발생합니다. 이는 부모이 여러 컴파일 단위로 정의되기 때문에 발생합니다. 해당 유닛이 서로 링크되면 LNK2005 오류가 발생합니다.템플릿 기반 템플릿이 아닌 클래스를 사용하면 LNK2005 오류가 발생합니다.
경우 당신이 궁금는 부모의 목적은 아이에게 모든 아이 예를 들어 하나의 정적 변수, 각 아이 < ''형 ''>에 대한 단지 하나를 제공하는 것입니다.
내 질문은 정적 변수 (모두 자식 인스턴스)에서 고유하고 여러 .cpp 파일에 포함될 수있는 템플릿 클래스를 어떻게 만듭니 까?
Apple.cpp#include "Apple.h"
#include "Banana.h"
#include <string>
void main() {
Apple apple;
Banana banana;
}
Apple.h
#ifndef APPLE_H
#define APPLE_H
struct Apple {
Apple();
};
#endif // APPLE_H
을
MAIN.CPP : 여기
이 LNK2005 오류가 발생 장난감 예제 Banana.h#ifndef BANANA_H
#define BANANA_H
struct Banana {
Banana();
};
#endif // BANANA_H
Banana.cpp
#include "Banana.h"
#include "Child.h"
Banana::Banana() {
Child<double> child;
child.foo(3.14);
}
Child.h
#ifndef CHILD_H
#define CHILD_H
#include <iostream>
using namespace std;
///////////// Parent Class Def ///////////
class Parent {
protected:
static int id;
};
int Parent::id = 0;
///////////// Child Class Def ///////////
template <class T>
struct Child : protected Parent {
Child();
void foo(T t);
};
template <class T>
Child<T>::Child() {
id++;
}
template <class T>
void Child<T>::foo(T t) {
cout << "Child" << id << "'s foo() says: " << t << endl;
}
#endif // CHILD_H
오류 LNK20 516,
#include "Apple.h"
#include "Child.h"
Apple::Apple() {
Child<int> child;
child.foo(5);
}
05 : Apple.obj에 이미 정의 된 "protected : static int Parent :: id"(? id @ Parent @@ 1HA)
내가 빨리 입력하는 법을 배워야한다고 생각합니다. 정확하게 +1하십시오. : P – Xeo
아 나는 그 생각을 했어야했다. 감사! – jok3rnaut