为什么我的对象没有被创建?
我如何从我的构造函数中执行 AllReferrals.push_back(this);
?
当我这样做时,有人告诉我
error C2065: 'AllReferrals' : undeclared identifier
还有
error C2228: left of '.push_back' must have class/struct/union
如果我把列表初始化放在我得到的类之前
error C2065: 'AllReferrals' : undeclared identifier
这是我的代码:
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 定义下。 无论如何,这始终是一个名称出现顺序问题。
关于C++ 保留对象列表并通过另一个函数调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1376186/