一个只能由另一堂课访问的课程

A Class to be accessed by another class only

本文关键字:访问 一个      更新时间:2023-10-16

我有一个声明一些静态变量的类:

#include <iostream>
class A
{
private:
static int x;
public:
static int y;
static getX(){ return A::x;}
static setX(int z){ A::x = z;}
};
int A::x = 0;
int A::y = 0;

现在,任何人/任何地方都可以访问A类,并且可以操纵其成员变量。我只能允许彼此允许访问类静态变量/方法的彼此类别?

class B
{
public:
void showX(){A::setX(9) ; std::cout << A::getX() << std::endl;}
void showY(){A::y = 8; std::cout << A::y << std::endl;}
};
int main()
{
B b1;
b1.showX();
b1.showY();
}

B中定义 A为私人类。

#include <iostream>
class B
{
    class A
    {
    private:
        static int x;
    public:
        static int y;
        static int getX() {
            return A::x;
        }
        static void setX(int z) {
            A::x = z;
        }
    };
public:
    void showX() {
        A::setX(9) ;
        std::cout << A::getX() << std::endl;
    }
    void showY() {
        A::y = 8;
        std::cout << A::y << std::endl;
    }
};
int B::A::x = 0;
int B::A::y = 0;
int main()
{
    B b1;
    b1.showX();
    b1.showY();
}

如果类仅在另一个类中才知道,那么我会说这应该是该类别的私人实现细节

class B
{
private:
    class A
    {
    private:
        static int x;
    public:
        static int y;
        static int getX(){ return A::x;}
        static void setX(int z){ A::x = z;}
    };
public:
    void showX(){A::setX(9) ; std::cout << A::getX() << std::endl;}
    void showY(){A::y = 8; std::cout << A::y << std::endl;}
};
int B::A::x = 0;
int B::A::y = 0;
int main()
{
    B b1;
    b1.showX();
    b1.showY();
}

现在,除B以外,任何人都不知道A的存在。

CRTP可以让您在不触摸B:

的情况下执行此操作
class B;
template<class A>
class A_shared_with_B {
private:
  static int y;
  static int getX(){ return A::x;}
  static void setX(int z){ A::x = z;}
  friend class B;
};
class A:public A_shared_with_B<A> {
  friend class A_shared_with_B<A>;
private:
  static int x;
};

现在B可以访问A_shared_with_Bprivate内容,A_shared_with_B可以访问Aprivate内容,并且B无法直接访问private的CC_12内容。

如果您愿意修改B并重命名A,则在Bprivate部分中命名A,使得该名称难以从外部B到达,这与上述访问控制相似。此技术的一个很好的优势是,您可以通过将A的其他无用实例传递给外部template函数来授予对A的代理访问:

template<class A>
void has_proxy_A_access( A ) {
  std::cout << A::getX();
}

B的实例可以调用has_proxy_A_access( A{} )并授予使用A的授予权,以给定(模板)函数。

已经有答案显示如何使A成为内部类。为了完整的目的,这里是private friend解决方案(Neil Butterworth的评论中已经提出):

#include <iostream>
class A {
private:
    friend class B;
    static int x;  
    static int y;
    static getX(){ return A::x;}
    static setX(int z){ A::x = z;}
};

friend可以访问类的所有成员,因此您可以使A的所有成员私有,并仅通过使其成为朋友来访问B