0

当我研究观察者设计模式的一个很好的例子时,我偶然发现了这段代码。总的来说,它会出错,地址是临时的[-fpermissive],坦率地说,我不明白它是什么。向函数发送类引用?这是真实生活吗?

#include <vector>
#include <iostream>
using namespace std;

class AlarmListener
{
  public:
    virtual void alarm() = 0;
};

class SensorSystem
{
    vector < AlarmListener * > listeners;
  public:
    void attach(AlarmListener *al)
    {
        listeners.push_back(al);
    }
    void soundTheAlarm()
    {
        for (int i = 0; i < listeners.size(); i++)
          listeners[i]->alarm();
    }
};

class Lighting: public AlarmListener
{
  public:
     /*virtual*/void alarm()
    {
        cout << "lights up" << '\n';
    }
};

class Gates: public AlarmListener
{
  public:
     /*virtual*/void alarm()
    {
        cout << "gates close" << '\n';
    }
};

class CheckList
{
    virtual void localize()
    {
        cout << "   establish a perimeter" << '\n';
    }
    virtual void isolate()
    {
        cout << "   isolate the grid" << '\n';
    }
    virtual void identify()
    {
        cout << "   identify the source" << '\n';
    }
  public:
    void byTheNumbers()
    {
        // Template Method design pattern
        localize();
        isolate();
        identify();
    }
};
// class inheri.  // type inheritance
class Surveillance: public CheckList, public AlarmListener
{
     /*virtual*/void isolate()
    {
        cout << "   train the cameras" << '\n';
    }
  public:
     /*virtual*/void alarm()
    {
        cout << "Surveillance - by the numbers:" << '\n';
        byTheNumbers();
    }
};

int main()
{
  SensorSystem ss;
  ss.attach(&Gates());
  ss.attach(&Lighting());
  ss.attach(&Surveillance());
  ss.soundTheAlarm();
}
4

1 回答 1

2

这是格式错误的:

ss.attach(&Gates());
         ^^^

Gates()是一个右值(特别是纯右值)。您不能获取右值的地址。它不是具有身份的对象,因此它实际上没有您可以获取的地址。语言阻止你做一些没有意义的事情。如果你确实存储了一个指向这个临时对象的指针,你最终会得到一个悬空指针,因为在这一行的末尾,临时对象Gates将被销毁。


由于SensorSystem拥有AlarmListener的 s,因此您必须预先创建它们:

Gates gates;
Lighting lighting;
Surveillance surveillance;

SensorSystem ss;
ss.attach(&gates);
ss.attach(&lighting);
ss.attach(&surveillance);
于 2016-03-03T14:42:26.190 回答