简体   繁体   English

访问指向类的指针的向量中的元素?

[英]Accessing an element in a vector of pointers to classes?

I have a vector containing pointers to several classes. 我有一个包含指向多个类的指针的向量。 The classes are defined as so: 这些类的定义如下:

class trackerSocket{
public:
    ~trackerSocket();

    int trackerInitialize(string address);
    int trackerSend(string getParams);
    int trackerRecv();

    be_node *responseDict;
    bool working;
    unsigned int interval;
    string trackerid;
    unsigned int complete;
    unsigned int incomplete;
    be_dict *peersDict;
    string peersBinary;
    bool dictionary;

private:
    string address;
    string port;
    string protocol;
    string page;
    SOCKET ConnectSocket;

    int parseAnnounce(string announce);
    int parseTrackerResponse(string response);
};

the vector is declared by this line: 向量由以下行声明:

vector<trackerSocket*> trackers;

and the classes are added to the vector using this line: 并使用以下行将类添加到向量中:

trackerSocket *temptracker = new trackerSocket();
//Initialize values in temptracker structure here (omitted)
trackers.push_back(temptracker);
//Reset temptracker
temptracker = new trackerSocket();
//Initialize values in temptracker structure here (omitted)
trackers.push_back(temptracker);
//Repeat

How can I access the working variable of each class in the vector? 如何访问向量中每个类的工作变量? The following code does not print working at all even though I know some of the classes have it set to true. 即使我知道某些类将其设置为true,以下代码也无法完全打印。

for(i = 0; i < trackers.size(); i++){
    if(trackers[i]->working){
        printf("Working.\n");
    }
}

Thanks for your help :) 谢谢你的帮助 :)

Try switching the line where you are allocating memory and the line where you are using push_back(). 尝试切换分配内存的行和使用push_back()的行。 Insertion may invalidate pointers in std::vector. 插入可能会使std :: vector中的指针无效。

Pointers to elements of std::vector and std::list 指向std :: vector和std :: list元素的指针

If think issue may be in scope in which initialization of instances of classes is perofrmed. 如果认为问题可能在于对类实例的初始化进行了研究。 As I know instances and therefore their members are initialized by zero values in namespaces, in static and in global scope, if you create instances of object on one of this scope this can lead to that filed working is init by default value "0" and I don`t wonder why 据我所知,实例及其成员是通过静态和全局作用域中的命名空间中的零值初始化的,如果您在该作用域之一上创建对象的实例,则可能导致默认情况下值为“ 0”初始化该字段的工作我不知道为什么

for(i = 0; i < trackers.size(); i++){
    if(trackers[i]->working){
        printf("Working.\n");
    }
} 
not working as you expect. If so I offer you to use default constructor.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM