【发布时间】:2013-02-22 23:33:48
【问题描述】:
因此,我已经做了几个小时的我认为会快速简单的项目,但我无法让它工作!这让我很沮丧,哈哈,我必须接近,但也许我不是。
我将在 cmets 中包含我的代码,解释它应该做什么。本质上它使用私有构造函数和析构函数。一个成员整数,然后是一个公共静态函数,用于返回对类中对象的引用 - 以及一个应该显示成员整数并递增它的公共函数。我不断收到范围和初始化错误。
这里有错误:
Singleton.h: In function ‘int main(int, char**)’:
Singleton.h:28:2: error: ‘Singleton::Singleton()’ is private
main.cpp:38:12: error: within this context
Singleton.h:29:2: error: ‘Singleton::~Singleton()’ is private
main.cpp:38:12: error: within this context
任何帮助或建议将不胜感激!
这是我的代码(Singleton.h、Singleton.cpp、main.cpp):
Singleton.h:
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
class Singleton {
public:
static Singleton& instance(); //returns a reference to a Singleton obj
void sendOutput(); //prints member variable and increments it
private:
int myInt; //member integer-variable
Singleton(); //constructor
~Singleton(); //destructor
};
#endif
Singleton.cpp:
#include <string>
#include "Singleton.h"
using namespace std;
//Displays to console that the obj was created. Initializes the member variable
Singleton::Singleton(){
myInt = 0; //member variable
cout << "Singleton Object Created!" << endl;
}
//destructor - displays to console that the Singleton object was destructed
Singleton::~Singleton(){
// delete myObj;
cout << "Singleton Object Destructed!" << endl;
}
//display member variable value and increment
void Singleton::sendOutput(){
cout << "Request to send data to output to console" << endl;
cout << "Integer Value: " << myInt << endl;
myInt++;
}
//REQUIRED: Static method with a reference to an object of this class return type
//create a static Singleton object and return it
Singleton& Singleton::instance(){
static Singleton myObj;
return myObj;
}
main.cpp:
#include "Singleton.h"
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
//Another requirement - demo static variables
void static_test(){
static int a = 1;
cout << a << endl;
a++;
}
int main(int argc, char * argv[]){
static_test();
static_test();
static_test();
//messed around with this for awhile - got it to work a few times
//messed it up a few more times O.o
Singleton mySingletonObj;
Singleton& sRef = Singleton::instance();
//sRef = Singleton::instance();
sRef.sendOutput();
return 0;
}
想法/建议/问题/疑虑? 任何事情都将有助于减轻这给我带来的挫败感,哈哈。给我造成这样的问题似乎太简单了。谢谢!
【问题讨论】:
-
myObj 在哪里定义? - 哦,我明白了。不,不要那样做。你不能在静态对象上调用 delete,否则会出现混乱......
-
我很确定 c-smile 对您的问题是正确的,但总的来说,请输入您得到的实际错误。
-
我摆脱了 delete myObj;我编辑了我的问题以添加我收到的错误。
-
为什么需要单例?只需创建一个对象并将其传递到需要的地方。
标签: c++ static static-methods object-reference private-constructor