我正在尝试为类FBLPost创建一个静态int变量currentId,这样每次创建FBLPost对象时,都会为新实例分配该id,并为下一个创建的新实例增加静态currentId 。我的构造函数在FBLPost.cpp中实现。这在java中是一项微不足道的任务,但是C ++让我很难过。我用Google搜索并查看过其他帖子,所以如果我错过了一些原谅我的话。这是我的代码和错误:
C:\Users\Dev\Desktop\myProjects\Assignment_3_220\Assignment3\FBLPost.h|31|error: 'int FBLPost::currentId' is not a static data member of 'class FBLPost'|
C:\Users\Dev\Desktop\myProjects\Assignment_3_220\Assignment3\FBLPost.cpp||In constructor 'FBLPost::FBLPost()':|
C:\Users\Dev\Desktop\myProjects\Assignment_3_220\Assignment3\FBLPost.cpp|5|error: 'currentId' was not declared in this scope|
||=== Build failed: 3 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|
当然没有声明currentId,我试图在这里声明它。
此外,如果我尝试删除static关键字,我仍会收到错误,如果我尝试在FBLPost中声明静态变量,我会收到错误。
FBLPost.h
#ifndef FBLPOST_H_INCLUDED
#define FBLPOST_H_INCLUDED
#include <stdio.h>
#include <string>
#include <stdlib.h>
class FBLUser;
using namespace std;
class FBLPost {
private:
string Post = "";
FBLPost* next = 0;
int likes = 0;
FBLUser* author;
int id;
public:
FBLPost();
string getPost();
void setPost(string p);
FBLPost* getNext();
void setNext(FBLPost* n);
int getLikes();
void incrementLikes();
void setAuthor(FBLUser* user);
FBLUser* getAuthor();
};
static int FBLPost::currentId = 0; //This line give me an error
#endif // FBLPOST_H_INCLUDED
FBLPost.cpp
#include "FBLPost.h"
using namespace std;
FBLPost::FBLPost() {
id = ++currentId;
}
string FBLPost::getPost() {
return Post;
}
void FBLPost::setPost(string p) {
Post = p;
}
FBLPost* FBLPost::getNext() {
return next;
}
void FBLPost::setNext(FBLPost* n) {
next = n;
}
int FBLPost::getLikes() {
return likes;
}
void FBLPost::incrementLikes() {
likes++;
}
void FBLPost::setAuthor(FBLUser* user) {
author = user;
}
答案 0 :(得分:0)
忽略更好的方法......你得到的错误是因为currentId 而不是被宣布为FBLPost的成员。
row