我想使用“策略”设计模式,并且只有一个简单的问题。
我们有两个类:Base
作为抽象类,Derived
作为具体类。
#include <iostream>
using namespace std;
class Base {
public:
virtual void func() = 0;
};
class Derived : public Base{
public:
virtual void func() override
{
printf("hello \n");
}
};
int main(){
Base * base = new Derived();
base->func();
Derived derived2;
Base & base2 = derived2;
base2.func();
return 0;
}
使用指针,
Base * base = new Derived();
使用引用
Derived derived2;
Base & base2 = derived2;
- 有什么办法可以写成一行供引用吗?
- 你们使用哪种方法来实现“策略”设计模式, 使用指针还是引用?
由于上述原因,我倾向于使用指针......但我希望专家解答。
最佳答案
Is there any way to write in one line for reference?
你可以使用 static_cast<Base&>
.这会产生对 Base
的引用你的对象的一部分:
int main() {
Derived derived2;
static_cast<Base&>(derived2).func();
return 0;
}
Which method are you guys use to implement the "strategy" design pattern, using pointer or reference?
您通常不会看到用于此的引用,因为大多数时候您需要存储多态对象,而这对于引用来说并不实用。引用引用一个对象,但该对象需要存在于其他地方。
请注意,您的第一个案例创建了一个动态分配的实例,您可以轻松地传递指针。第二个创建一个本地对象,它更难以多态方式四处移动。如果您尝试存储您的 Derived
将对象放入容器中,无论如何您肯定需要动态分配它。尝试否则将导致 object slicing (派生部分被完全切掉)。
例如,这就是您存储 Derived
的方式放入 Base
的容器中指针:
int main()
{
std::vector<std::unique_ptr<Base>> my_bases;
my_bases.emplace_back(std::make_unique<Derived>());
}
如果您尝试使用 std::vector<Base>
它不会编译( Base
是抽象的)。但即使它确实编译了(通过使 Base
具体化),它也不会表现出多态性。这不是策略模式独有的。每当您使用多态性时,它就是这样工作的。
关于c++ - 在 C++ 中使用引用进行向上转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614131/