【发布时间】:2018-10-06 04:59:05
【问题描述】:
它是生成器类的头;
#ifndef GENERATOR_H
#define GENERATOR_H
class Generator
{
public:
Generator(int);
~Generator();
int getBits();
private:
int bits;
};
#endif // GENERATOR_H
。 它是代理类的头文件,是Generator驱动的单例类;
#ifndef PROXY_H
#define PROXY_H
#include "Generator.h"
class Proxy: private Generator
{
public:
~Proxy();
static Proxy* getInstance(int);
Generator * operator ->();
int checkvalue();
private:
Proxy();
Proxy(int);
int bits;
int counter;
static Proxy* instance;
Generator * rPointer;
};
#endif // GENERATORPROXY_H
。 这是代理的 CPP 文件。
Proxy::Proxy(int inputbits):Generator(inputbits)
{
}
Proxy::~Proxy()
{
}
Generator * Proxy::operator ->()
{
counter++;
if(counter<=10)
return rPointer;
else
return 0;
}
Proxy* Proxy::instance = 0;
Proxy* Proxy::getInstance(int inputbits)
{
if(instance==0)
{
instance = new Proxy(inputbits);
}
return instance;
}
问题:当我在 main 函数中创建一些代理对象时,如何在 main 函数中调用 getBits() 函数?
这是主要功能的一部分:
Proxy* px = Proxy::getInstance(4);
cout << px->getBits() << endl;
当我尝试它时,错误发生如下:int Generator::getBits() is inaccessible. Generator is not an accessible base of Proxy.
我可以在 main 中访问生成器的方式,我制作了这样的运算符:Generator * Proxy::operator ->(),它位于代理的 CPP 文件中。如何访问 main 函数中的 getBits() 函数?谢谢大家的帮助。
【问题讨论】:
-
为什么是继承
private Generator? -
@RobertAndrzejuk 这是单例类的声明,以防止任何用户访问 Generator 类。
-
你刚刚回答了你自己的问题。
-
嗯,所以你的意思是我不能访问生成器类中的函数?我想将 Generator 类的访问限制为 10 次。
-
我需要调用函数在main函数中使用operator->,可以吗?
标签: c++ inheritance singleton private