#include <iostream>
template <class T>
class singleton
{
public :
static T* instance() {sinstance = new T; return sinstance;}
private :
static T* sinstance;
singleton(singleton const&);
singleton& operator=(singleton const&);
protected:
singleton();
~singleton() {delete sinstance;}
};
template <class T> T* singleton<T>::sinstance=NULL;
class circle
{public:
circle(int radius) { pointer = new int; *pointer = radius ;}
circle(const circle &r) { pointer = new int; *pointer=*r.pointer;}
~circle() { delete pointer;}
circle& operator=(const circle&pr)
{ *pointer =*pr.pointer; }
int getData(){ return *pointer;}
private:
int *pointer;
};
typedef singleton<circle> circlesingleton;
int main()
{
circle(7);
circlesingleton::instance()->getData();
}
Hi. Я делаю домашнее задание с использованием одноэлементного класса. Как это сделать? Im начинающий. И этот код - это код, который я ищу в Интернете и добавляю к нему какую-то часть. Спасибо. Первый класс в одноэлементном классе, который я использую в качестве шаблона. Класс круга в классе наш профессор сказал нам, чтобы использовать каноническую формуsingleton как шаблон, undefined error
Errors :
project1singleton.cpp: In instantiation of ‘static T*
singleton<T>::instance() [with T = circle]’:
project1singleton.cpp:40:19: required from here
project1singleton.cpp:7:51: error: no matching function for call to
‘circle::circle()’
static /*singleton*/ T* instance() {sinstance = new T /*singleton*/ ;return
sinstance;}
^
project1singleton.cpp:7:51: note: candidates are:
project1singleton.cpp:26:7: note: circle::circle(const circle&)
circle(const circle &r) { pointer = new int; *pointer=*r.pointer;}
^
project1singleton.cpp:26:7: note: candidate expects 1 argument, 0 provided
project1singleton.cpp:25:7: note: circle::circle(int)
circle(int radius) { pointer = new int; *pointer = radius ;}
^
Возможный дубликат [Почему шаблоны могут быть реализованы только в файле заголовка?] (Http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header- файл). –
Вы не разместили ошибки, в любом случае 'sinstance = new T' не будет работать для' circle', потому что 'circle' не имеет конструктора по умолчанию, а' circle & operator = (const circle & pr) 'ничего не возвращает. – user657267
@ user657267 привет. Я просто добавляю свои ошибки. Итак, каждый раз, когда я вызываю getData(), выполняется выполнение по умолчанию круга? Но если я добавлю circle() {return * pointer;}, то ошибка будет project1singleton.cpp: 24: 26: error: возврат значения из конструктора circle() {return * pointer;} – tiger