我尝试遵循DRY,我想在函数中初始化一个新类,但有一个问题,我的类是一个父类,我在这个函数中初始化新的派生类。
样品:
类声明:
#include <iostream>
class parent
{
private:
int m_number;
public:
parent() {}
virtual void say_hello() { std::cout << "Hello. This is parent class!" << std::endl; }
~parent() {}
};
class derived1 : public parent
{
public:
derived1(){}
void say_hello() override { std::cout << "Hello. This is first derived class!" << std::endl; }
~derived1(){}
};
class derived2 : public parent
{
public:
derived2() {}
void say_hello() override { std::cout << "Hello. This is second derived class!" << std::endl; }
~derived2() {}
};
枚举状态:
enum OutputMethod
{
STATE_NONE,
STATE_CLASS,
STATE_EXIT
};
测试措施:
#include <Windows.h>
#define VK_L_C 0x43
#define VK_L_N 0x4E
void action(OutputMethod &state)
{
if (GetKeyState(VK_L_C) < 0)
{
state = STATE_CLASS;
}
else if (GetKeyState(VK_L_N) < 0)
{
state = STATE_NONE;
}
else if (GetKeyState(VK_ESCAPE) < 0)
{
state = STATE_EXIT;
}
}
主要:
#include <iostream>
#include <string>
int main(void)
{
derived1 *p_derived = nullptr;
OutputMethod out_method;
out_method = STATE_NONE;
while (out_method != STATE_EXIT)
{
// Actions (C-class, N-none, ESC-endloop)
action(out_method);
//--------BEGINING of desired function----------
if (out_method == STATE_NONE)
{
std::cout << "Hello from main!" << std::endl;
}
else if (out_method == STATE_CLASS)
{
if (p_derived == nullptr)
{
// There is the problem (derived1 name should be variable)
p_derived = new derived1();
}
p_derived->say_hello();
}
if (out_method == STATE_NONE)
{
if (p_derived != nullptr)
{
delete p_derived;
p_derived = nullptr;
}
}
//-------------END of desired function----------
}
if (p_derived != nullptr)
{
delete p_derived;
p_derived = nullptr;
}
std::string exit = "";
std::getline(std::cin, exit);
return 0;
}
我不知道该怎么做。
我试着创建一个函数来处理这个问题:
void output_state(parent *p_variable, parent* p_new, OutputMethod state_0, OutputMethod state_1, OutputMethod &state)
{
if (state == state_0)
{
std::cout << "Hello from main!" << std::endl;
}
else if (state == state_1)
{
if (p_variable == nullptr)
{
// There is the problem (p_new is not a name var but a new object init)
p_variable = p_new;
}
p_variable->say_hello();
}
if (state == state_0)
{
if (p_variable != nullptr)
{
delete p_variable;
p_variable = nullptr;
}
}
}
在main中调用:
...
derived1 *p_derived = nullptr;
OutputMethod out_method;
out_method = STATE_NONE;
while (out_method != STATE_EXIT)
{
// Actions (C-class, N-none, ESC-endloop)
action(out_method);
output_state(p_derived, new derived1(), STATE_NONE, STATE_CLASS, out_method);
}
...
但问题是,我不想每次调用函数时都初始化一个新对象,而且我不确定如何进行检查,以便能够调用函数,但同时防止初始化新对象。
我错过什么了吗?
P.S:很抱歉长的代码,但当我发布一个短代码,我得到的答复,人们无法阅读我的想法,但如果我张贴所有必要的部分,我得到的答复,代码太长,无法阅读.
1条答案
按热度按时间ygya80vv1#
看起来你想让你的函数生成一个给定类型的对象。
template
可以做到这一点:在main中:
请注意,我将
p_variable
保留为原始指针,但使用std::unique_ptr<>
更安全。