简体   繁体   English

简化重载的类函数

[英]simplifying overloaded class function

I am having in my class gTexture two functions declared: 我在类gTexture中声明了两个函数:

public:
                               gTexture():mActiveTexture(0){...}
   virtual void                DrawTexture();
   virtual void                DrawTexture(unsigned short int TextureNumber);
           int                 mActiveTexture;

where 哪里

void gTexture::DrawTexture()
    {
    gTexture::DrawTexture(mActiveTexture);
    }

I'd like to have this in one function something like 我想在一个功能中有这样的东西

virtual void                DrawTexture(unsigned short int TextureNumber=mActiveTexture);

This does no compile as mActiveTexture is an invalid use of non static data member. 这不会编译,因为mActiveTexture是对非静态数据成员的无效使用。 Is there any way to just have one function, which would make it easier to handle with my derived objects? 有什么方法可以只具有一个函数,这将使我的派生对象更容易处理? Thanks. 谢谢。

I can see two ways. 我可以看到两种方式。 Both are workaround-ish, but could be useful. 两者都可以解决,但可能很有用。

One is to make the parameterless function non-virtual; 一种是使无参数函数成为非虚拟函数; it will simply always call the second one with mActiveTexture . 它将始终总是使用mActiveTexture调用第二个。

The other way is to use domain knowledge (specifically the fact that 0 is not a valid OpenGL texture name) and do this: 另一种方法是使用领域知识(特别是0不是有效的OpenGL纹理名称这一事实)并执行以下操作:

virtual void DrawTexture(unsigned short int TextureNumber = 0) {
  if (TextureNumber == 0) TextureNumber = mActiveTexture;
  // ... rest of the code
}

You could have a default argument value that is not valid (eg -1). 您可能有一个无效的默认参数值(例如-1)。 Then your function can check if that value is the default and if it is, use mActiveTexture, otherwise it will use the argument. 然后,您的函数可以检查该值是否为默认值,如果是默认值,请使用mActiveTexture,否则它将使用该参数。

No, you can't use members as defaults. 不,您不能使用成员作为默认值。 Defaults are used at compile time. 默认值在编译时使用。

You could however use a special value for the default, like -1 and then check in DrawTexture if the input values is -1 and if so set it to mActiveTexture. 但是,您可以为默认值使用特殊值,例如-1,然后在DrawTexture中检查输入值是否为-1,如果输入为-1,则将其设置为mActiveTexture。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM