C++ 如何访问类的静态成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4104544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access static members of a class?
提问by sorush-r
I am starting to learn C++ and Qt, but sometimes the simplest code that I paste from a book results in errors.
我开始学习 C++ 和 Qt,但有时我从书中粘贴的最简单的代码会导致错误。
I'm using g++4.4.2
on Ubuntu 10.04 with QtCreator IDE. Is there a difference between the g++ compiler syntax and other compilers? For example when I try to access static members something always goes wrong.
我g++4.4.2
在 Ubuntu 10.04 上使用 QtCreator IDE。g++ 编译器语法和其他编译器有区别吗?例如,当我尝试访问静态成员时,总是会出错。
#include <iostream>
using namespace std;
class A
{
public:
static int x;
static int getX() {return x;}
};
int main()
{
int A::x = 100; // error: invalid use of qualified-name 'A::x'
cout<<A::getX(); // error: : undefined reference to 'A::x'
return 0;
}
I think it's exactly the same as declared hereand here(isn't it?). So what's wrong with the above code?
回答by Flexo
You've declared the static members fine, but not definedthem anywhere.
您已经声明了静态成员很好,但没有在任何地方定义它们。
Basically what you've said "there exists some static member", but never set aside some memory for it, you need:
基本上你所说的“存在一些静态成员”,但永远不要为它留出一些内存,你需要:
int A::x = 100;
Somewhere outside the class and notinside main.
在班级之外的某个地方,而不是在主要的内部。
回答by Prasoon Saurav
Section [9.4.2]
第 [9.4.2] 节
Static Data Members
静态数据成员
The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member's class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the
::
operator
静态数据成员在其类定义中的声明不是定义,并且可能是除 cv 限定的 void 之外的不完整类型。 静态数据成员的定义应出现在包含成员类定义的命名空间范围内。在命名空间范围的定义中,静态数据成员的名称应使用
::
运算符由其类名限定
回答by Martin York
Try:
尝试:
#include <iostream>
using namespace std;
class A
{
public:
// This declares it.
static int x;
static int getX(){return x;}
};
// Now you need an create the object so
// This must be done in once source file (at file scope level)
int A::x = 100;
int main()
{
A::x = 200;
// Note no int here. You can modify it
cout<<A::getX(); // Should work
return 0;
}
回答by Shubham Singh
You need to define the static member variable of the class outside the class as static member variables require declaration as well as definition.
您需要在类之外定义类的静态成员变量,因为静态成员变量需要声明和定义。
#include <iostream>
using namespace std;
class A
{
public:
static int x;
static int getX() {return x;}
};
int A::x; // STATIC MEMBER VARIABLE x DEFINITION
int main()
{
A::x = 100; // REMOVE int FROM HERE
cout<<A::getX();
return 0;
}
回答by Naresh
Try this example:
试试这个例子:
#include<iostream>
using namespace std;
class check
{
static int a;
public:
void change();
} ;
int check::a=10;
void check::change()
{
a++;
cout<<a<<"\n";
}
int main()
{
int i,j;
check c;
check b;
c.change();
b.change();
return 0;
}
回答by Oliver Charlesworth
The definition of static member variables must live at file scope, i.e. outside all functions, etc.
静态成员变量的定义必须存在于文件范围内,即在所有函数之外等。
回答by CashCow
Now you have worked out how to use static class members I will advise you that you should generally use them only in the following circumstances:
现在您已经了解了如何使用静态类成员,我建议您通常只在以下情况下使用它们:
For use in templates. So in your example you could have GetX() in different classes and in a template somewhere you would use
template< typename T > int func() { return T::GetX(); }
although obviously more elaborate. But here your static function being in a class serves a purpose.
Where the function needs access to the class, i.e. to private members. You could make it a friend but you may as well make it static. Often the case in callbacks.
用于模板。因此,在您的示例中,您可以在不同的类和模板中使用 GetX()
template< typename T > int func() { return T::GetX(); }
虽然显然更精细。但是在这里你的静态函数在一个类中是有目的的。
函数需要访问类的地方,即私有成员。你可以让它成为朋友,但你也可以让它成为静态的。在回调中经常出现这种情况。
The rest of the time you can probably use compilation-unit level functions and variables which has the advantage of taking your members out of the header (particularly if they are private). The less implementation detail you give the better.
其余时间您可能可以使用编译单元级别的函数和变量,它们的优点是将您的成员从头中取出(特别是如果它们是私有的)。你提供的实现细节越少越好。
回答by Eswaran Pandi
Case 1: static variable
案例一:静态变量
As we all know, defining a static variable inside a class which will throw compilation error. E.g. below
众所周知,在类中定义静态变量会引发编译错误。例如下面
class Stats
{
public:
static int AtkStats[3];
*static int a =20;* // Error: defining a value for static variable
};
int Stats::AtkStats[3] = {10, 0, 0};
Output:
输出:
error: ISO C++ forbids in-class initialization of non-const static member 'Stats::a'
Case 2: const static variable
案例 2:const 静态变量
For conststatic variable, we can define a value either inside a class or Outside class.
对于const静态变量,我们可以在类内部或类外部定义一个值。
class Stats
{
public:
static const int AtkStats[3];
static const int a =20; // Success: defining a value for a const static
};
const int Stats::AtkStats[3] = {10, 0, 0};
const int Stats::a = 20; // we can define outside also
Output:
输出:
Compilation success.