次のコードは、書籍 "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