c++ - 可以将类引用作为参数发送给函数吗?

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

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

最佳答案

这是错误的:

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

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


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

Gates gates;
Lighting lighting;
Surveillance surveillance;

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

关于c++ - 可以将类引用作为参数发送给函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35775138/

相关文章:

c++ - 奇异矩阵的高斯消元

java - 在数据集合上运行流程的良好设计模式?

c++ - Win32 MVC 模式实现

c# - .Net 观察者模式改变。这些是什么时候发生的,为什么?

c++ - 传入 A::operator new() 的大小是否总是等于 sizeof(A)?

c++ - CUDA C++ : Using a template function which calls a template kernel

c++ - 如何在不使用系统复制命令的情况下将可执行文件的二进制代码复制到新文件中?

c++ - 工厂模式和 std::bind 方法

java - 如何为 web 应用程序创建客户端通知服务或者我应该使用观察者模式?

ruby - 同时具有 ActiveResource 和 ActiveRecord 的 Rails 审计系统