为什么不创建我的对象?
以及如何从构造函数中执行AllReferrals.push_back(this);
?
当我这样做的时候,我被告知
错误C2065:“ AllReferrals”:未声明的标识符
以及
错误C2228:“。push_back”的左侧必须具有class / struct / union
如果我将列表初始化放在类之前
错误C2065:“ AllReferrals”:未声明的标识符
这是我的代码:
class Referral
{
public:
string url;
map<string, int> keywords;
static bool submit(string url, string keyword, int occurrences)
{
//if(lots of things i'll later add){
Referral(url, keyword, occurrences);
return true;
//}
//else
// return false;
}
private:
list<string> urls;
Referral(string url, string keyword, int occurrences)
{
url = url;
keywords[keyword] = occurrences;
AllReferrals.push_back(this);
}
};
static list<Referral> AllReferrals;
int main()
{
Referral::submit("url", "keyword", 1);
}
最佳答案
当您从上至下读取文件时,必须在使用AllReferrals名称之前对其进行声明。
如果未声明,则编译器不知道它存在。这就是错误的意思。
要解决您的问题,只需在使用声明之前移动声明,然后为需要名称但尚未定义的类型使用“转发声明”。
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <list>
#include <map>
using namespace std;
using namespace tr1;
class Referral; // forward declaration
list<Referral> AllReferrals; // here 'static' is not needed
class Referral
{
public:
string url;
map<string, int> keywords;
static bool submit(string url, string keyword, int occurrences)
{
//if(lots of things i'll later add){
Referral(url, keyword, occurrences);
return true;
//}
//else
// return false;
}
private:
list<string> urls;
Referral(string url, string keyword, int occurrences)
{
url = url;
keywords[keyword] = occurrences;
AllReferrals.push_back(this);
}
};
int main()
{
Referral::submit("url", "keyword", 1);
cout << AllReferrals.size();
cout << "\n why does that ^^ say 0 (help me make it say one)?";
cout << "\n and how can i AllReferrals.push_back(this) from my constructor?";
cout << " When I do it like so, I am told error C2065: 'AllReferrals' : undeclared identifier";
cout << " as well as error C2228: left of '.push_back' must have class/struct/union.";
cout << " If I put the list initialization before the class I get error C2065: 'AllReferrals' : undeclared identifier.";
cout << "\n\n\t Thanks!";
getchar();
}
正如评论者所添加的,另一种解决方案是将构造函数定义移到AllReferrals定义下。
无论如何,这始终是名称分配命令的问题。