我正在尝试访问类对象向量中的元素,但我没有把它弄好。我想这是构造函数/解构函数和引用的错误,但甚至其他问题,如C++ destructor issue with std::vector of class objects,c++ vector of class object pointers或C++ vector of objects vs. vector of pointers to objects。希望有人可以帮我修改我的代码片段。
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;
};
#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;
}
#include "node.h"
class Com {
public:
std::vector<Node> nodes;
Com();
com(const Com& orig);
virtual ~Com();
void cout_nodes(void);
private:
};
#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++ vector of objects vs. vector of pointers to objects一样,当我使用引用时一切正常,但我无法让std::iterator
和find_if
工作。
find_if
statement and index calculationauto 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
会对其论点进行复制,因此您可以复制伪造的副本。
而不是强制定义一个编译器可以很容易地自己合成的操作(你只有一个int
和一个std::string
作为成员),而不是声明它。
或者,如果你想要显式(或者需要,例如使用默认的c'tor),只需显式默认它:
class Node {
Node() = default;
Node(const Node& orig) = default;
};