San*_*lin 20 c++ static private class member
假设我有一个.hpp文件,其中包含一个带有公共静态方法和私有静态成员/变量的简单类.这是一个示例类:
class MyClass
{
public:
static int DoSomethingWithTheVar()
{
TheVar = 10;
return TheVar;
}
private:
static int TheVar;
}
Run Code Online (Sandbox Code Playgroud)
当我打电话给:
int Result = MyClass::DoSomethingWithTheVar();
Run Code Online (Sandbox Code Playgroud)
我希望"结果"等于10;
相反,我得到(在第10行):
undefined reference to `MyClass::TheVar'
Run Code Online (Sandbox Code Playgroud)
第10行是"TheVar = 10;" 从方法.
我的问题是它是否可以从静态方法(DoSomethingWithTheVar)访问私有静态成员(TheVar)?
Pie*_*aud 23
对你的问题的回答是肯定的!您只是错过了定义静态成员TheVar:
int MyClass::TheVar = 0;
Run Code Online (Sandbox Code Playgroud)
在cpp文件中.
它是尊重一个定义规则.
示例:
// Myclass.h
class MyClass
{
public:
static int DoSomethingWithTheVar()
{
TheVar = 10;
return TheVar;
}
private:
static int TheVar;
};
// Myclass.cpp
#include "Myclass.h"
int MyClass::TheVar = 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18205 次 |
| 最近记录: |