真小学生水平想要问问代码究竟什么问题,为什么总是报错

才新学的知识类;
#pragma once
#include
#include<atlstr.h>
using namespace std;

class cClient {
public:
cClient() {
ClientNum++;
}
void SetServerName(string server);
void GetServerName();
void SetName(CString name);
void GetName();
~cClient() { }
private:
static string Server;//保留所连接的服务器的名称
static int ClientNum;//记录已经实例化对象的数量
CString Name;

};
#include"client.h"
void cClient::SetServerName(string server) {
Server = server;
}
void cClient::GetServerName() {
cout << "所连接的服务器为:" << Server << endl;
}
void cClient::SetName(CString name) {
Name = name;
}
void cClient::GetName() {
cout << "实例化对象名称为:" << Name << endl;
}
int cClient::ClientNum = 0;
#include
#include"client.h"
using namespace std;
int main() {
cClient c1;
c1.SetServerName("CSBQ");
c1.GetServerName();
c1.SetName("1号");
c1.GetName();

return 0;

}

我这边编译出来的问题是:

img


原因:
私有的静态成员变量只能在外部进行初始化,你的ClientNum变量已经初始化了,但是你的Server却在构造里头赋值,这个是错误的。
解决:

  • 方法一
    你可以将Server变量声明为普通的成员变量,这样就可以在构造中赋值或者成员初始化列表进行初始化。
  • 方法二
    Server不在构造中赋值,同ClientNum一样在外部进行初始化。