【发布时间】:2016-12-23 09:13:11
【问题描述】:
我知道这个问题已经得到解答。但我只是想确认一下我的理解。
这是我的 sn-p 代码。来自this。
#include <iostream>
using namespace std;
class Base
{
void a() { cout << "a "; }
void c() { cout << "c "; }
void e() { cout << "e "; }
// 2. Steps requiring peculiar implementations are "placeholders" in base class
virtual void ph1() = 0;
virtual void ph2() = 0;
public:
// 1. Standardize the skeleton of an algorithm in a base class "template method"
virtual ~Base() = default;
void execute()
{
a();
ph1();
c();
ph2();
e();
}
};
class One: public Base
{
// 3. Derived classes implement placeholder methods
/*virtual*/ void ph1() { cout << "b "; }
/*virtual*/ void ph2() { cout << "d "; }
};
class Two: public Base
{
/*virtual*/ void ph1() { cout << "2 "; }
/*virtual*/ void ph2() { cout << "4 "; }
};
int main()
{
Base *array[] =
{
&One(), &Two()
};
for (int i = 0; i < 2; i++)
{
array[i]->execute();
cout << '\n';
}
}
当我编译时,它给出了错误作为标题:
error: taking address of temporary [-fpermissive]
&One(), &Two()
error: taking address of temporary [-fpermissive]
&One(), &Two()
所以,我尝试在互联网上查找。正如他们所说:
&A() 正在创建一个临时对象,该对象在退出完整表达式时自动销毁...
当我换了error line
&One(), &Two()
到
new One(), new Two()
然后,它起作用了。
但是,我如何使原始代码像作者写的那样工作?我应该使用delete吗
delete array[i];
【问题讨论】:
-
你必须弄清楚你想在这里问哪个问题。您目前正在询问两个不相关的问题。
标签: c++