64,637
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include "Game.h"
using namespace std;
class Player;
extern Game* game;
Game* game = 0;
Player* p1;
class RedBall
{
public:
RedBall()
{
cout<<"RedBall"<<endl;
}
};
class Player
{
public:
Player(){}
void Fire()
{
game->addBall<RedBall>();
}
};
int main()
{
Game* game = new Game();
p1 = new Player();
p1->Fire();
return 0;
}
#pragma once
class Game
{
public:
Game(){}
template<typename T>
void addBall();
};
#include "Game.h"
template<typename T>
void Game::addBall()
{
RedBall* p = new T;
}
linux-6v95:/home/owenliang/csdn/cAndCpp # g++ -o game.o -c game.cpp
linux-6v95:/home/owenliang/csdn/cAndCpp # g++ -o main.o -c main.cpp
linux-6v95:/home/owenliang/csdn/cAndCpp # g++ -o main main.o game.o
linux-6v95:/home/owenliang/csdn/cAndCpp # ./main
linux-6v95:/home/owenliang/csdn/cAndCpp #
linux-6v95:/home/owenliang/csdn/cAndCpp # cat game.h
#ifndef GAME_H
#define GAME_H
class Game
{
public:
Game(); //normal mem-function
template <class T> //template-mem-function
void addBall(T n)
{
//implement
}
};
#endif
linux-6v95:/home/owenliang/csdn/cAndCpp # cat game.cpp
#include "game.h"
Game::Game()
{
//mem-function-implement
}
linux-6v95:/home/owenliang/csdn/cAndCpp # cat main.cpp
#include "game.h"
int main()
{
Game game;
game.addBall(3);
game.addBall(3.5);
return 0;
}
linux-6v95:/home/owenliang/csdn/cAndCpp #