gpt4 book ai didi

c++ - 如何使用静态对象和方法!? C++ 挫折

转载 作者:搜寻专家 更新时间:2023-10-31 01:11:20 26 4
gpt4 key购买 nike

所以我已经花了几个小时来完成我认为会快速简单的项目,但我无法让它工作!这让我很沮丧,哈哈,我必须接近,但也许我不是。

我将在我的代码中附上注释,解释它应该做什么。本质上它使用私有(private)构造函数和析构函数。一个成员整数,然后是一个公共(public)静态函数,用于返回对类中对象的引用 - 以及一个应该显示成员整数并递增它的公共(public)函数。我不断收到范围和初始化错误。

这里是错误:

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;
}

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;
}

想法/建议/问题/疑虑?任何事情都将有助于减轻这给我带来的挫败感,哈哈。给我造成这样的问题似乎太简单了。谢谢!

最佳答案

在该范围内禁止:

Singleton mySingletonObj;

应该没问题:

Singleton& sRef = Singleton::instance();

引用不可重新分配:

sRef = Singleton::instance();

应该没问题:

sRef.sendOutput();

另外,删除这个——语言已经指定了对象的生命周期和存储,并负责销毁它:

delete myObj;

您还应该删除复制类型的能力:

Singleton(); //constructor
Singleton(const Singleton&) = delete; // deleted copy constructor

关于c++ - 如何使用静态对象和方法!? C++ 挫折,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15035032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com