假设我们有以下类:
class A {
static SomeLongType b;
};
现在我们需要在相应的cpp文件中对其进行初始化。我能想到以下几种方法:
SomeLongType A::b{}; // repetition of SomeLongType
decltype(A::b) A::b{}; // A::b written two times
对我来说,这两种方式都有点繁琐。有没有更好的方法呢?
auto
。但正如ecatmur所评论的那样,这在该语言中是不允许的。#define DEFINE(x) decltype(x) x{}
struct A
{
static SomeLongType b;
};
DEFINE( A::b );
我真的很讨厌C宏,但在某些情况下它们是有用的。
#define DEFINE(x) decltype(x) x
,然后使用 DEFINE(A::b);
、DEFINE(A::b){ 一些参数 };
或者 DEFINE(A::b) = something;
。我认为这比 #define DEFINE(X , params...)
DEFINE(A::b , p1 , p2 , p3, etc )
更清晰,更灵活,也不容易出错。 - Manu343726
public::
。 :) - herohuyongtaoauto
会很好,但请参考https://dev59.com/PGYq5IYBdhLWcg3wrihD?rq=1。 - ecatmurstatic
变量需要一个定义。 - harperdecltype
,我们可以假设您在使用 C++11 吗?我已经编辑了标签。 - John Dibling