结构体需要访问类的私有实例变量
C++ - Struct needs access to private instance variable of class
我的c++有点生疏,所以我想知道你是否可以帮助我。基本上,我有两个结构体和一个类,结构体需要访问类的私有实例变量。
#ifndef TREE_H
#define TREE_H
#include <iostream>
struct Node {
...
inline void addEdge(Edge* e);
};
inline void Node::addEdge(Edge* e) {
char ch = inp[e->startIndex];
edges[ch] = e;
}
struct Edge {
Node* next = new Node();
int startIndex = 0;
friend std::ostream& operator<<(std::ostream& out, Edge e) {
int index = inp.size() - e.startIndex + endIndex + 1; // Here the edge needs access to the private members of the Tree class such as string inp, and int endIndex
// ... do things with index
return out;
}
};
class Tree {
public:
Tree();
friend std::ostream& operator<<(std::ostream& out, Tree s);
private:
Node* root = nullptr;
int endIndex = 0;
std::string inp;
void foo();
std::ostream& printTree(std::ostream& out, Node* curr, std::string append="");
};
#endif // TREE_H
显然上面的代码不起作用。我想把结构体移到类里面。然后是<<Edge的操作符给了我一个"无效使用非静态数据成员'endIndex'"错误。我确信将工作的一个想法是传递一个引用/指针到endIndex作为Edge的成员,当我创建Edge,但我想知道什么可能是一个更好的方法去做这个
我建议使用访问者模式。
这里有一个简短的,不完整的例子,给你一个概念:
class Tree
{
Node _Node;
std::list<Node> _Children;
public:
... // other stuff, like AddChild(), etc.
void Traverse(Visitor visitor)
{
visitor.HandleNodeData(_Node.Data);
traverseChildren(visitor);
}
};
我还会考虑将Tree类实现为模板
对于任何人将来的参考,我现在使用指针解决方案;似乎能完成任务。我对此唯一的疑问是,Tree类中的endIndex是否一定需要在堆栈上(我认为它需要)。有人能解释一下吗?
#ifndef TREE_H
#define TREE_H
#include <iostream>
struct Node {
...
inline void addEdge(Edge* e);
};
inline void Node::addEdge(Edge* e) {
char ch = inp[e->startIndex];
edges[ch] = e;
}
struct Edge {
Edge(int start, int* endIndex) {
this->startIndex = start;
this->endIndex = endIndex;
}
Node* next = new Node();
int startIndex = 0;
int* endIndex;
friend std::ostream& operator<<(std::ostream& out, Edge e) {
std::string value = inp.substr(e.startIndex, *e.endIndex - e.startIndex + 1);
out << "(---- " << value << "[" << e.startIndex << ", " << *e.endIndex << "] ---->)";
return out;
}
};
class Tree {
public:
Tree();
friend std::ostream& operator<<(std::ostream& out, Tree s);
private:
Node* root = nullptr;
int* endIndex = new int; // am i correct in saying this needs to be on the stack?
std::string inp;
void foo();
std::ostream& printTree(std::ostream& out, Node* curr, std::string append="");
};
#endif // TREE_H
相关文章:
- 返回 C++ 中的指针实例变量
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- C++ 实例变量初始值设定项中的重复类型
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- C++ 中实例变量的双冒号
- 我可以在没有任何实例变量的情况下使用 decltype 吗?
- OpenMP 私有类实例变量
- C 取消实例变量指针
- 在C++私有区域中初始化实例变量
- 如何将指针存储在实例变量中,该指针被声明为指向基类的指针
- 如何在Arduino中创建另一个类库的实例变量
- 单元测试呼叫实例变量的函数
- 为构造函数初始化引用实例变量提供默认值
- 如何使编译器在实例变量未初始化时C++生成错误或警告
- 如何超载分配运算符,该操作员总计两个实例变量
- C++:通过引用传递或使用私有实例变量
- 对象作为类内的实例变量
- 在不构造实例变量的情况下C++声明实例变量的好方法是什么?
- 实例变量列表中的对象未被保留?指针问题
- Asio完成处理程序中的实例变量无效