防止成员函数被单独调用

时间:2015-09-06 14:48:20

标签: c++ function class

在此代码中:

class Person {
    std::string name;
public:
    Person(const std::string& n) : name(n) {}
    void setName(const std::string& newName) {name = newName;}
};

class System {
    void changeName (Person* person, const std::string& newName) {
        person->setName(newName);  // The obvious necessary line.
        // A bunch of very important changes due to the name change.
    }
};

每当一个人改名时,必须在System进行一系列更改。如果没有其他变化,一切都会崩溃。但是,很容易忘记这一点,并偶然意外地打电话给Person::setName。如何让那不可能?我想到了密钥传递习语,但这仍然不能阻止Person调用自己的Person::setName函数(我也不希望System成为Person的朋友})。如果这样的保护是不可能的,如何重新设计这样就不会发生这样的事故(而且很可能会因为我的记忆不那么好)?

1 个答案:

答案 0 :(得分:3)

您可以使用the Observer pattern。在最基本的版本中,让每个Person保持指向System的指针,并在调用某个人的setName()时通知System,以便它执行某些操作非常重要的变化:

class System; // forward declaration
class Person {
    std::string name;
    System* system;

public:
    Person(const std::string& n, System* s) : name(n), system(s) {}
    void setName(const std::string& newName);
};

class System {
public:
    void changeName (Person* person, const std::string& newName) {
        person->setName(newName);  // The obvious necessary line.
    }
    void onNameChange(Person* person) {
        // A bunch of very important changes due to the name change.
    }
};

void Person::setName(const std::string& newName) {
    name = newName;
    system->onNameChange(this); // notify the system
}