所以我已经做了几个小时我认为会快速简单的项目,但我无法让它工作!这让我很沮丧,哈哈,我必须接近,但也许我不是。
我将在我的代码中包含解释它应该做什么的注释。本质上它使用私有构造函数和析构函数。一个成员整数,然后是一个公共静态函数,用于返回对类中对象的引用 - 以及一个应该显示成员整数并递增它的公共函数。我不断收到范围和初始化错误。
以下是错误:
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):
单例.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
单例.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;
}
主.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;
}
想法/建议/问题/疑虑?任何事情都将有助于减轻这给我带来的挫败感,哈哈。给我造成这样的问题似乎太简单了。谢谢!