当我研究Observer Design模式的一个很好的例子时,我偶然发现了这段代码。在主要的,它得到错误,采取临时[-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();
}
答案 0 :(得分:2)
这是不正确的:
ss.attach(&Gates());
^^^
Gates()
是一个右值(特别是一个prvalue)。你不能取rvalue的地址。它不是具有身份的对象,因此它实际上没有您可以使用的地址。这种语言阻止你做一些没有意义的事情。如果你确实存储了一个指向这个临时的指针,你最终会得到一个悬空指针,因为在这一行的末尾,临时Gates
将被销毁。
由于SensorSystem
不拥有其AlarmListener
,因此您必须预先创建它们:
Gates gates;
Lighting lighting;
Surveillance surveillance;
SensorSystem ss;
ss.attach(&gates);
ss.attach(&lighting);
ss.attach(&surveillance);