重写-如何减少键入

Overriding - how to do it with less typing?

本文关键字:何减少 重写      更新时间:2023-10-16

假设我有

class A
{
public:
   virtual void Muhahahaha(int a, float f, Object C, Smth else, Etc etc);
};

class B: public A
{
public:
   virtual void Muhahahaha(int a, float f, Object C, Smth else, Etc etc) override;
};

现在,困扰我的是,每次重写基类成员函数时,我都必须重新键入整个参数列表。为什么我不能写这样的东西:

virtual void Muhahahaha override;

编译器只知道我想要什么?当然,除了只有一个哈哈哈哈的情况。。。

有这样的办法吗?

有这样的办法吗?

是的,但你永远不能这样做。

我不会

听着,如果我给你看这个,你照做了,我的声誉就会受损。。。

承诺

他们会因为我向你展示。。。

请继续。。。?

好的,那么:

#define OBFUSCATE Muhahahaha(int a, float f, double C, char etc)
class A
{
public:
    virtual void OBFUSCATE;
};
class B: public A
{
public:
    virtual void OBFUSCATE override;
};
void A::OBFUSCATE
{
    // try to debug this
}
void B::OBFUSCATE
{
    // try to debug this too!
}

问题是在一个函数中获取了太多参数。这对每个函数都不好,无论是否为虚拟函数。

作为一个通常可以缓解这个问题的解决方案的例子,为什么不将int a, float f, Object C, Smth else, Etc etc捆绑到一个类中呢?像这样:

struct Parameters
{
    int a;
    float f;
    Object C;
    Smth Else;
    Etc etc;
};

那么你要做的打字就少了:

class A
{
public:
   virtual void Muhahahaha(Parameters const& arguments);
};
class B : public A
{
public:
   void Muhahahaha(Parameters const& arguments) override;
};

事实上,"每次都必须重新键入整个参数列表"只是一种症状。一旦重构了代码,使得参数列表变短,问题就会自行消失。