gpt4 book ai didi

c++ - 在没有对象参数的情况下调用非静态成员函数会发生错误

转载 作者:行者123 更新时间:2023-12-02 10:34:55 25 4
gpt4 key购买 nike

我正在尝试创建与动态数组相关的应用程序。我试图让实例为我的数组调用函数,但它给了我错误:

error: call to non-static member function without an object argument



getInstance()函数的类型有问题吗?

这是我的标题和主文件:

dynamic_array.h
    #ifndef DYNAMIC_ARRAY_H
#define DYNAMIC_ARRAY_H

template <class T>
class DynamicArray{
private:
T *arr;
static int instance;

public:
int getInstance();
};

template <typename T>
int DynamicArray<T>::getInstance(){
if(instance == 0){
//...
}
return instance;
}

template <typename T>
int DynamicArray<T>::instance = 0;

#endif // DYNAMIC_ARRAY_H

main.cpp
#include "dynamic_array.h"

int main(){

DynamicArray<int> *array = DynamicArray<int>::getInstance(); // Error occurs here

return 0;
}

最佳答案

我猜您正在尝试一次实现设计模式Singleton和 vector (一种动态数组)。

那这个呢:

dynamic_array.h

#ifndef DYNAMIC_ARRAY_H
#define DYNAMIC_ARRAY_H

#include <iostream>

template <class T>
class DynamicArray
{
private:
static DynamicArray* instance;
T* arr;

/* singleton pattern
forbid outside access to constructor */

DynamicArray();
DynamicArray(size_t size_of_array);
~DynamicArray();

public:
static void createInstance(size_t size_of_array);
static DynamicArray<T>* getInstance();
static void destroyInstance();
};

template <class T>
DynamicArray<T>* DynamicArray<T>::instance = nullptr;

// singleton methods

template<class T>
inline void DynamicArray<T>::createInstance(size_t size_of_array)
{
if (instance) return;
instance = new DynamicArray(size_of_array);
}

template <typename T>
DynamicArray<T>* DynamicArray<T>::getInstance()
{
// might be nullptr if not initialized

return instance;
}

template<class T>
inline void DynamicArray<T>::destroyInstance()
{
// delete check for nullptr on its own

delete instance;
}

// constructor

template<class T>
inline DynamicArray<T>::DynamicArray(size_t size_of_array)
{
std::cout << "DynamicArray's been constructed.\n";
arr = new T[size_of_array];
}

// destructor

template<class T>
inline DynamicArray<T>::~DynamicArray()
{
delete[] arr;
std::cout << "DynamicArray's destructor has been called.\n";

// instance is still alive
}

#endif

main.cpp
#include "dynamic_array.h"

int main()
{
DynamicArray<int>::createInstance(10);
DynamicArray<int>* instance = DynamicArray<int>::getInstance();

// do something with instance

/* manually call destructor,
so that if more pointers are pointing to instance
they have no access to a delete call */

DynamicArray<int>::destroyInstance();

return 0;
}

关于c++ - 在没有对象参数的情况下调用非静态成员函数会发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60718668/

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