授予对另一个类的访问权限而不暴露它

Hum*_*awi 0 c++ design-patterns

我有一节课让我们称之为Person:

class Person{
private:
    void move(x,y,z);
}
Run Code Online (Sandbox Code Playgroud)

我有另一个叫做的课PersonController:

class PersonController{
public:
    void control(){
        while(some_thing){
             //do some calculations
             controlled_person_->move(some_values); //Wrong Accessing to a private member
        }
    }
private:
    Person* controlled_person_;
}
Run Code Online (Sandbox Code Playgroud)

这两个PersonPersonController是我设计的库的公共接口的一部分.

我希望PersonController能够打电话movePerson.但是,我不希望任何人move从公共接口访问此函数().

解决问题的简单方法是添加友谊,以便PersonController访问私人成员Person.但是,据我所知,friend没有引入关键字来解决这些问题,在这里使用它将是一个不好的做法.

  • 它是否正确?我应该避免friend在这里吗?
  • 这是否意味着我的设计被打破了?
  • 还有其他建议吗?

Sto*_*ica 5

从您在评论中所说的内容来看,您似乎只PersonController对触及该成员函数感兴趣.这样做的方法就是公开,但为它添加一个私钥:

class Person{
public:
    class MovePrivilege {
        move_privilege() = default; // private c'tor
        friend class PersonController; // only PersonController may construct this
    }; 

    void move(MovePrivilege, x,y,z);
};

class PersonController{
public:
    void control(){
        while(some_thing){
             //do some calculations
             controlled_person_->move(MovePrivilege{} , some_values);
        }
    }
private:
    Person* controlled_person_;
};
Run Code Online (Sandbox Code Playgroud)

该类型MovePrivilege有私人c'tor.所以它只能由它的朋友构建.它也是呼叫所必需的move.因此,虽然move是公开的,但唯一可以称之为的朋友是MovePrivilege.

这基本上可以让您对谁可以调用移动进行细致的控制.如果这是突兀的,你不能改变移动本身,那么律师客户习语的变体可能是合适的.

您可以随意使用.Direct firend-ship只是最直接的工具.