嘿傢伙。感謝點擊。我正在努力與包括。基本上,我正在嘗試創建一個模板類,其中有一個函數可以接受該模板的特定實例。我做了以下人爲的例子來說明這一點。轉發聲明/包含模板類 - 「不完整類型的無效使用」
比方說,我有一個標記有模板(通用)類型數據的個人世界。我有一個特定的個人,稱爲國王。所有的個人都應該能夠在國王面前跪下。一般來說,個人可以被標記爲任何東西。國王以數字標記(第一,第二位國王)。
的誤差
g++ -g -O2 -Wall -Wno-sign-compare -Iinclude -DHAVE_CONFIG_H -c -o Individual.o Individual.cpp
g++ -g -O2 -Wall -Wno-sign-compare -Iinclude -DHAVE_CONFIG_H -c -o King.o King.cpp
In file included from King.h:3,
from King.cpp:2:
Individual.h: In member function ‘void Individual<Data>::KneelBeforeTheKing(King*)’:
Individual.h:21: error: invalid use of incomplete type ‘struct King’
Individual.h:2: error: forward declaration of ‘struct King’
make: *** [King.o] Error 1
Individual.h(Individual.cpp爲空)
//Individual.h
#pragma once
class King;
#include "King.h"
#include <cstdlib>
#include <cstdio>
template <typename Data> class Individual
{
protected:
Data d;
public:
void Breathe()
{
printf("Breathing...\n");
};
void KneelBeforeTheKing(King* king)
{
king->CommandToKneel();
printf("Kneeling...\n");
};
Individual(Data a_d):d(a_d){};
};
King.h
//King.h
#pragma once
#include "Individual.h"
#include <cstdlib>
#include <cstdio>
class King : public Individual<int>
{
protected:
void CommandToKneel();
public:
King(int a_d):
Individual<int>(a_d)
{
printf("I am the No. %d King\n", d);
};
};
King.cpp
//King.cpp
#include "King.h"
#include <string>
int main(int argc, char** argv)
{
Individual<std::string> person("Townsperson");
King* king = new King(1);
king->Breathe();
person.Breathe();
person.KneelBeforeTheKing(king);
}
void King::CommandToKneel()
{
printf("Kneel before me!\n");
}
的Makefile
CXX = g++
CXXFLAGS = -g -O2 -Wall -Wno-sign-compare -Iinclude -DHAVE_CONFIG_H
OBJS = Individual.o King.o
test: $(OBJS)
$(CXX) -o [email protected] $^
clean:
rm -rf $(OBJS) test
all: test
我在想我的設計是不正確的,因爲我碰到的問題似乎有點人爲的問題。我需要一個模板化的課程的原因是存儲模板化的數據(一個國王被標記爲第N個國王,一個人被標記爲字符串作爲他們的名字,另一種類型的人可以被標記爲人的號碼,即人# 234" )。有沒有辦法存儲模板化的數據,而無需製作模板類? – SharkCop 2010-11-21 20:00:44
@TheChariot:默認情況下(除非您在代碼中聲明)模板實例化是不相關的類。如果您有一個想要用語言表達的概念(「個人」),並且符合該概念的不同實體共享通用功能,請考慮使用繼承。基類不會有任何存儲的數據,每個派生類將添加特定的數據(一個普通人的字符串,一個未命名人員的數字......)在你的設計中,儘管他們共享一些方法,「Individual」和'個人'不能通過相同的接口傳遞。 –
2010-11-22 09:00:33