防止单独调用成员函数
Preventing a member function from being called alone
在此代码中:
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
本身。如何让这成为不可能?我想到了key-pass习语,但这仍然不能阻止Person
调用自己的Person::setName
函数(我也不希望System
成为Person
的朋友)。如果这样的保护措施是不可能的,那么如何重新设计它,使这样的事故不会发生(它很可能会发生,因为我的记忆力不是那么好)?
您可以使用观察者模式。在最基本的版本中,让每个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
}
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法