以下代码是书籍“Design Patterns Explained Simply”中的一个示例。我试图用其他问题的建议方式,但结果不好。我怎样才能找出这个问题:警告:以临时地址 - C++
commands[0] = &SimpleCommand(&object, &Number::dubble);
“警告:以临时地址”?
#include <iostream>
#include <vector>
using namespace std;
class Number
{
public:
void dubble(int &value)
{
value *= 2;
}
};
class Command
{
public:
virtual void execute(int &) = 0;
};
class SimpleCommand: public Command
{
typedef void(Number:: *Action)(int &);
Number *receiver;
Action action;
public:
SimpleCommand(Number *rec, Action act)
{
receiver = rec;
action = act;
}
/*virtual*/void execute(int &num)
{
(receiver->*action)(num);
}
};
class MacroCommand: public Command
{
vector < Command * > list;
public:
void add(Command *cmd)
{
list.push_back(cmd);
}
/*virtual*/void execute(int &num)
{
for (unsigned int i = 0; i < list.size(); i++)
list[i]->execute(num);
}
};
int main()
{
Number object;
Command *commands[3];
commands[0] = &SimpleCommand(&object, &Number::dubble); // "warning: taking address of temporary"
MacroCommand two;
two.add(commands[0]);
two.add(commands[0]);
commands[1] = &two;
MacroCommand four;
four.add(&two);
four.add(&two);
commands[2] = &four;
int num, index;
while (true)
{
cout << "Enter number selection (0=2x 1=4x 2=16x): ";
cin >> num >> index;
commands[index]->execute(num);
cout << " " << num << '\n';
}
}
不要将C作为标记添加到标记为C++,C++ 11,C++ 14的问题中 –
请给出我确切的错误和报告这个错误的地方 – YSC
@JonathanLeffler我甚至不确定它应该被标记为C++ 11或C++ 14甚至是visual-C++。 – YSC