Привет, ребята. Спасибо, что нажали. Я борюсь с включает. По сути, я пытаюсь создать класс шаблона, в котором есть функция, которая принимает конкретный экземпляр этого шаблона. Я сделал следующий надуманный пример, чтобы проиллюстрировать это.
Скажем, у меня есть мир людей, помеченных шаблонным (универсальным) типом данных. У меня есть конкретный человек, называемый королем. И все люди должны быть в состоянии встать на колени перед королем. Физические лица, как правило, могут быть помечены как что-либо. Короли отмечены числами (1-й, 2-й король).
Ошибка
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 $@ $^
clean:
rm -rf $(OBJS) test
all: test