gpt4 book ai didi

c++ - 防止成员函数被单独调用

转载 作者:行者123 更新时间:2023-11-28 00:12:14 25 4
gpt4 key购买 nike

在这段代码中:

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.
}
};

每当一个人改变他的名字时,必须在系统中做一堆改变。如果没有那些其他的变化,一切都会崩溃。然而,很容易忘记这一点,不小心自己调用了 Person::setName。如何使这不可能?我想到了 key-pass 习语,但这仍然不能阻止 Person 调用它自己的 Person::setName 函数(我也不想要 System 成为 Person 的 friend )。如果这样的保护措施是不可能的,如何重新设计它,使这样的事故不会发生(而且很可能会发生,因为我的内存力不太好)?

最佳答案

您可以使用 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
}

关于c++ - 防止成员函数被单独调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32424771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com