这是声明文件MyImage.h:
#pragma once
template <class Pixel>
class MyImage
{
public:
MyImage();
MyImage(unsigned int w, unsigned int h);
MyImage(const MyImage<Pixel>& copie);
~MyImage();
MyImage<Pixel>& operator=(const MyImage<Pixel>& image); //quand on utilise la variable MyImage, il faut écrire MyImage<Pixel>
int getWidth() const;
int getHeight() const;
//resize(int w, int h);
//T* operator[](int){return _bitmap+ i*_width;} adresse du 1er element de la ligne
private:
int _width;
int _height;
Pixel *_bitmap;
};
这是定义文件MyImage.cpp:
#include "MyImage.h"
template <class Pixel>
MyImage<Pixel>::MyImage() : _width(0), _height(0), _bitmap(NULL)
{}
template <class Pixel>
MyImage<Pixel>::MyImage(unsigned int w, unsigned int h) : _width(w), _height(h)
{
_bitmap = new Pixel[w*h];
}
template <class Pixel>
MyImage<Pixel>::MyImage(const MyImage<Pixel>& copie) : MyImage(_width, _height)
{
for (int i = 0; i < _width*_height; i++)
{
_bitmap[i] = copie._bitmap[i];
}
// ou _bitmap = new bitmap(*(copie._bitmap));
}
template <class Pixel>
MyImage<Pixel>::~MyImage()
{
delete _bitmap;
}
template <class Pixel>
MyImage<Pixel>& MyImage<Pixel>::operator=(const MyImage<Pixel>& image)
{
if (this != &image)
{
_width = image._width;
_height = image._height;
delete _bitmap;
for (int i = 0; i < _width*_height; i++)
{
_bitmap[i] = copie._bitmap[i];
}
// ou _bitmap = new bitmap(*(copie._bitmap));
}
return *this;
}
template <class Pixel>
int MyImage<Pixel>::getWidth() const
{
return _width;
}
template <class Pixel>
int MyImage<Pixel>::getHeight() const
{
return _height;
}
这是main.cpp的主要功能:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include "MyImage.h"
using namespace std;
int main()
{
MyImage<unsigned char> image(20,20); // 0-255
//MyImage<unsigned char> image1(image);
return 0;
}
我有一些错误,如:
1>------ Build started: Project: TP5 Template Image, Configuration: Debug Win32 ------
1> MyImage.cpp
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall MyImage<unsigned char>::MyImage<unsigned char>(unsigned int,unsigned int)" (??0?$MyImage@E@@QAE@II@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall MyImage<unsigned char>::~MyImage<unsigned char>(void)" (??1?$MyImage@E@@QAE@XZ) referenced in function _main
1>D:\TPCPP\TP5 Template Image\Debug\TP5 Template Image.exe : fatal error LNK1120: 2 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
在main函数中,我试图声明“MyImage image();”它没关系,但它不适用于“MyImage image(20,20);”
有人可以帮助我吗?
答案 0 :(得分:0)
将类成员函数定义放在定义模板类的同一标头中。