C++ 使用静态非成员函数中的静态常量成员
我在类中有一个私有的static const成员,在类实现中我有一个尝试使用这个const的静态函数,但它给了我错误C++ 使用静态非成员函数中的静态常量成员,c++,class,static-members,C++,Class,Static Members,我在类中有一个私有的static const成员,在类实现中我有一个尝试使用这个const的静态函数,但它给了我错误 //A.hpp class A { static const int X = 1; //<<problem here // .... } //A.hpp 甲级{ static const int X=1;//您正试图从自由函数访问a的私有成员。这是不允许的 你应该把它公开,例如: class A { public: static cons
//A.hpp
class A {
static const int X = 1; //<<problem here
// ....
}
//A.hpp
甲级{
static const int X=1;//您正试图从自由函数访问a
的私有成员。这是不允许的
你应该把它公开,例如:
class A {
public:
static const int X = 1;
}
杰克回答的另一个解决方案是将函数DoSomething()
设置为非静态函数,并将其声明为a类的friend
:
//A.hpp
class A {
static const int X = 1;
// ....
friend int DoSomething();
};
//A.cpp
int DoSomething() {
int n = A::X;
//....
}
但是我不想公开它…它只供你在课堂上使用,因为课堂上的东西不是课堂的一部分,所以你的要求不符合。或者声明<代码> DoSomething <代码> > <代码>朋友> <代码> > A类< /C>。请发布一些语法上有效的C++代码。也许你是应该将其更改为public:static const int X=1;
是A.hpp
重要的内容还是键入错误?
//A.hpp
class A {
static const int X = 1;
// ....
friend int DoSomething();
};
//A.cpp
int DoSomething() {
int n = A::X;
//....
}