多态结构声明 [英] polymorphic struct declaration

查看:124
本文介绍了多态结构声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这个问题已经被问及回答了,但是我没有正确的术语搜索。

I am sure that this question has been asked and answered before, but I am having trouble searching without the proper terminology.

我有两个独特的结构A& B(而不是类)。我的代码使用功能重载来处理结构不同。我不明白如何处理声明的多态性。我为一个伪代码示例道歉。

I have two unique structs A & B (not classes). My code uses functional overloading to treat the structs differently. I don't understand how to handle the declaration polymorphism. I apologize for a pseudocode example.

if( flag ==1 ){
   declare stuct A scoped to main
}
else{
   declare stuct B scoped to main
}

因为声明在if语句中有作用域,所以上面的代码不起作用。我的真正的代码不编译,因为我想要描述的范围问题。

The pseudo code above will not work since the declarations are scoped within the if statements. My "real" code doesn't compile because of the scoping issues I am trying to describe.

EDIT

说明:

根据指定的标志(arg),我想声明两个不同的结构体之一。一旦正确的结构被声明了所有的多态性已经由操作重载处理。

Depending on a specified flag (arg) I want to declare one of two different structs. Once the proper struct is declared all polymorphism is already handled by operation overloading.

谢谢

推荐答案

这个问题根本上与结构体,类或多态无关,(虽然解决方案确实需要后者)。

This question fundamentally has nothing to do with structs, or classes, or polymorphism, (though the solution does require the latter).

有条件地声明不同类型的对象,而不会与块作用域相撞。简单的答案是你不能。

It's about trying to declare objects of different types, conditionally, without running afoul of block scoping. The simple answer is that you can't.

通常的方法是使用一个后期初始化的智能指针:

The usual approach is to use a late-initialised smart pointer instead:

#include <memory>
#include <cstdlib>

struct A { virtual ~A() {} };
struct B : A {};
struct C : A {};

void f(A&);

int main()
{
   srand(time(0));
   const int x = rand();

#if 0
   /** Can't do this: **/
   if (x > 500)
      B obj;
   else
      C obj;

   f(obj);
#endif

   /** Can do this: **/
   std::unique_ptr<A> ptr;
   if (x > 500)
      ptr.reset(new B);
   else
      ptr.reset(new C);

   f(*ptr);

#if 0
   /** Some older examples may propose this: **/
   A* ptr = NULL;
   if (x > 500)
      ptr = new B;
   else
      ptr = new C;

   f(*ptr);

   delete ptr;
   ptr = NULL;
#endif
}

由于 f 接受一个引用,即使你喂它一个 A

Since f accepts a reference, polymorphic is maintained even though you're feeding it a A.

通常,你实际上通过 ptr 调用成员函数,使用虚拟分派来确保执行正确的代码:

Typically you'd actually invoke a member function through ptr, using virtual dispatch to ensure that the correct code is executed:

   std::unique_ptr<A> ptr;
   if (x > 500)
      ptr.reset(new B);
   else
      ptr.reset(new C);

   ptr->someFunction();

不需要重载功能。

这篇关于多态结构声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆