【问题标题】:It is possible to send class reference as an argument to a function?可以将类引用作为参数发送给函数吗?
【发布时间】:2016-06-16 22:53:32
【问题描述】:

当我研究观察者设计模式的一个很好的例子时,我偶然发现了这段代码。总的来说,它会出错,地址是临时的[-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();
}

【问题讨论】:

  • 您在哪里使用参考文献?我看到的一切都是你在使用指针。

标签: c++ design-patterns observer-pattern class-reference


【解决方案1】:

这是格式错误的:

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

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


由于SensorSystem拥有它的AlarmListeners,您必须预先创建它们:

Gates gates;
Lighting lighting;
Surveillance surveillance;

SensorSystem ss;
ss.attach(&gates);
ss.attach(&lighting);
ss.attach(&surveillance);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-05
    • 2023-04-01
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多