一个只能由另一堂课访问的课程
A Class to be accessed by another class only
我有一个声明一些静态变量的类:
#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_B
的private
内容,A_shared_with_B
可以访问A
的private
内容,并且B
无法直接访问private
的CC_12内容。
如果您愿意修改B
并重命名A
,则在B
的private
部分中命名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
。
相关文章:
- 我们可以访问一个不存在的联盟的成员吗
- 无法从 Visual Studio C++ 中的另一个类访问一个类
- 可以访问一个类中的播放器结构,但不能访问另一个类中的播放器结构
- 从另一个类访问一个类的私有成员
- 从另一个类 Qt 访问一个类
- C++:一个写入器/多个读取器访问一个unordered_map线程安全
- 通过单个实例从多个类访问一个类
- 我如何访问一个对象的向量的成员变量,该对象是从类中的成员变量
- 我所有应用程序类都可以访问一个对象
- 如何在另一个函数中访问一个函数中的变量
- 如何从另一个函数中访问一个功能,从C 中的第三个访问
- C :如何使一组派生的类能够访问一个类的私人成员
- 如何在不使用友元类的情况下通过另一个类访问一个类的私有成员
- 多读访问一个std::map,将导致不安全的行为
- 如何从另一个类访问一个类的方法/变量,而不在c++中实例化它或子类
- 如何在另一个类中访问一个类的成员函数
- C++程序在访问一个巨大的数组时会冻结
- 访问一个向量,该向量是映射中的一个值,以使用另一个向量在其上运行相等运算符
- 在 VC++ 中访问一个文件中声明的变量.(外部关键字用法)
- 代码库是什么意思?以及我如何访问一个