C++ 保留对象列表并通过另一个函数调用构造函数

标签 c++ list object constructor private

为什么我的对象没有被创建?
我如何从我的构造函数中执行 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/

相关文章:

c++ - 如何连接文件路径?

c++ - 调整大小时数组 "breaks"

python - 如何访问列表元素

javascript - 将参数传递给 forEach.call 中的函数

c++ - 如何可移植(反)序列化 qint32?

c++ - gcc 警告和 gcc 错误消息之间的区别

Python:列表匹配

java - 如果迭代已经同步,是否有必要使用synchronizedList而不是List?

c++ - 具有标识号和连接的对象 vector

C++ 列表迭代器访问同一对象中的不同元素