使用单例 class 作为派生 class 时如何访问基 class 中的函数

How to access the function in base class when using singleton class as a derived class

它是一个header的生成器class;

#ifndef GENERATOR_H
#define GENERATOR_H


class Generator
{
    public:
        Generator(int);
        ~Generator();
        int getBits();

    private:
        int bits;
};

#endif // GENERATOR_H

。 它是代理 class 的 header,它是从生成器驱动的单例 class;

#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函数中做一些代理object时,如何在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 的方式,我做了这样的运算符: Generator * Proxy::operator ->() 在用于代理的 CPP 文件中。如何访问主函数中的 getBits() 函数?谢谢大家的帮助。

要使用 Proxy::operator->,您必须先取消引用 px。所以 (*px)->getBits() 应该可以解决问题。

正如 Eduard Rostomyan 所说,您应该使用组合而不是继承,因为代理 不是 生成器。

此外,您没有在代码示例和代码中的任何位置设置 rPointer。

问题 1:

继承是 private,这意味着从基础 Generator class 开始的所有内容都将进入 Proxy class 的 private 部分. 如果 Generator 中的 public 函数是可见的,那么你需要继承 public -要么- 在 Proxy 中创建一个 public 函数,它调用 Generator

中所需的函数

问题 2:

当我们需要在特定上下文中使用 Derived classes(很多时候未知 classes)时,使用继承。 Base class 代表所有 Derived class 背后的抽象概念。它被用作所有 Derived classes 之间的 "common" 概念。

换句话说:GeneratorProxy 的抽象 - 或者 - ProxyGenerator 的特定类型。 如果没有,那么我会使用组合(使其成为 Proxy 中的变量)。

问题 3:

评论里对Generatorclass的访问次数也有要求。通过继承,Generator class 必须控制对它的所有访问。

所以这就是为什么你有 Proxy class。这是一个额外的间接级别 - 它是你的 Generator class 的包装器,它应该将所有调用委托给它。

Proxy class 应该有所有需要调用的函数。它是 Generator class 的 "protector" (这可能就是为什么使用 private 继承的原因)。


这些问题是设计问题,你必须决定什么是最好的。