簡體   English   中英

C ++訪問類對象向量中的元素

[英]C++ accessing element in vector of class objects

我正在嘗試訪問類對象向量中的元素,但我沒有把它弄好。 我想構造函數/解構函數和引用有問題,但即使是其他問題,如C ++析構函數問題,類對象的std :: vector,類對象指針的c ++向量對象的 C ++向量與指向對象的指針向量 希望有人可以幫我修改我的代碼片段。

node.h

class Node {

public:
    Node();
    Node(int id, const std::string& name);
    Node(const Node& orig);
    virtual ~Node();

    void cout(void);

    int get_id(void);

private:
    int _id;
    std::string _name;

};

node.cpp

#include "node.h"

Node::Node() {
}

Node::Node(int id, const std::string& name) : _id(id), _name(name) {
    this->cout();
}

Node::Node(const Node& orig) {
}

Node::~Node() {
}

void Node::cout(void) {
    std::cout << "NODE " << _id << " \"" << _name << "\"" std::endl;
}

int Node::get_id(void) {
    return _id;
}

communication.h

#include "node.h"

class Com {

public:
    std::vector<Node> nodes;

    Com();
    com(const Com& orig);
    virtual ~Com();

    void cout_nodes(void);

private:

};

communication.cpp

#include "communication.h"

Com::Com() {
    nodes.push_back(Node(169, "Node #1"));
    nodes.push_back(Node(170, "Node #2"));
}

Com::Com(const Com& orig) {
}

Com::~Com() {
}

void Com::cout_nodes(void) {
    for (uint8_t i = 0; i < nodes.size(); i++) {
        nodes[i].cout();
    }
}

如果我運行Com com; 我得到了預期的輸出:

[I 171218 13:10:10 Cpp:22] < NODE 169 "Node #1"
[I 171218 13:10:10 Cpp:22] < NODE 170 "Node #2"

但是運行com.cout_nodes(); 結果是:

[I 171218 13:10:14 Cpp:22] < NODE 0 ""
[I 171218 13:10:14 Cpp:22] < NODE 0 ""

就像C ++向量對象與指向對象指針的向量一樣,當我使用引用時,一切正常,但是我無法使std::iteratorfind_if工作。

更新:工作find_if語句和索引計算

auto iterator = std::find_if(nodes.begin(), nodes.end(), [&](Node node) {
    return node.get_id() == 169;
});

if (iterator != nodes.end()) {
    size_t index = std::distance(nodes.begin(), iterator );
    std::cout << "Index of ID #169: " << index << std::endl;
}

您定義了此復制構造函數:

Node::Node(const Node& orig) {
}

它沒有做任何復制。 它默認初始化正在構造的Node所有成員。 由於std::vector::push_back會復制其參數,因此您的get偽造副本。

而不是強制定義一個編譯器可以很容易地自己合成的操作(你只有一個int和一個std::string作為成員),而不是聲明它。

或者,如果你想要顯式(或者需要,例如使用默認的c'tor),只需顯式默認它:

class Node {

    Node()                 = default;
    Node(const Node& orig) = default;

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM