简体   繁体   English

实现没有作用域解析运算符的类?

[英]Implement class without scope resolution operator?

If I declare my class in a header file, is there any way to implement the class without all those annoying scope resolution operators? 如果我在头文件中声明我的类,没有所有那些烦人的作用域解析运算符,有没有办法实现该类? I don't like rewriting the class name for each member. 我不喜欢为每个成员重写类名。 I think I have tried to do it like this before: 我想我以前曾经尝试过这样做:

In Ah 在啊

#if !defined(a_h)
#define a_h
class A {
    int function (int);
    int foo (void);
};
#endif

In A.cpp 在A.cpp中

#include "A.h"
class A { 
     int function (int number) {
         return 2* number;
     }
    int foo (void){
        return 2;
    }
}

but got some error (unable to test it now unfortunately). 但出现了一些错误(很遗憾,现在无法对其进行测试)。

You can use pre-processor macros to make it easier. 您可以使用预处理器宏来简化操作。

#include "A.h"
#ifdef _
#undef _
#endif
#define _(fun) A::fun

int _(function)(int number)
{
   return 2* number;
}

int _(foo)(void)
{
   return 2;
}

However ... 但是...

You shouldn't necessarily do something just because you can. 您不必仅仅因为可以就做某事。

Using a preprocessor macro to hide an important construct of the language is ill-advised. 不建议使用预处理器宏来隐藏语言的重要构造。 Here are some things to think about before you go down that path. 在走这条路之前,这里有一些需要考虑的事情。

  1. The time spent writing <ClassName>:: fades in comparison to the amount time spent in writing rest of the code in any program that does something useful. 与在任何有用的程序中编写其余代码所花费的时间相比,编写<ClassName>::花费的时间逐渐减少。

  2. The amount of time you will spend in debugging and maintaining a program will be much much higher than the amount of time you'll spend in writing <ClassName>:: . 您花费在调试和维护程序上的时间将比编写<ClassName>::花费的时间高得多。

  3. When you have multiple classes in a .cpp file, you will have a hard time clearly seeing which function corresponds to which class if you adopt the same policy for all classes. .cpp文件中有多个类时,如果对所有类采用相同的策略,则很难清楚地看到哪个函数对应于哪个类。

  4. When you are debugging, you will be frustrated that you won't be able to see the fully qualified function name when you step into a function. 调试时,您会感到沮丧,因为您进入某个功能后将看不到完全限定的功能名称。

  5. The loss of clarity is too expensive a price to pay in exchange for saving a few key strokes while implementing the member functions of a class. 清晰度的损失太昂贵了,要付出代价以换取在实现类的成员功能时节省一些按键的代价。

I am speaking from experience. 我说的是经验。 I work in a project where one of the class names is INR_DynamicallyTypedLowFidelityLeafComponentRepresentation . 我在一个项目名称为INR_DynamicallyTypedLowFidelityLeafComponentRepresentation的项目中工作。 I wouldn't use a preprocessor macro to hide even that long a name. 我不会使用预处理器宏来隐藏这么长的名称。

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

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