类中具有此类类型的参数
Parameter in class that has this class type
class Vertex {
public:
Vertex* previous_vertex_id;
Vertex::Vertex() {}
Vertex::~Vertex() {}
}
现在它可以编译,但我需要严格previous_vertex_id没有指针,它用于使用此属性的进一步代码。我怎样才能做到这一点?
你不能有一个以自身为成员的类,这样的对象的大小将是无限的。包含Vertex
的Vertex
,其中包含Vertex
等。
从这个问题以及您之前发布的一个问题来看,您似乎想要类似 java 的东西,但C++。你想要这样的东西:
class Vertex {
public:
Vertex* previous_vertex_id;
...
void setPrevious(Vertex &v) {
previous_vertex_id = &v;
}
Vertex &getPrevious() {
return (*previous_vertex_id); // trusting that the pointer will still be valid.
}
}
现在,重要的是要知道何时在C++中复制对象以及何时引用对象。对于我刚才描述的Vertex
类:
Vertex v1{}; // construct a new vertex
Vertex v2{}; // construct a new vertex
// v3 is a copy of v1, they are separate objects at different memory locations.
Vertex v3 = v1;
// v4 is a reference to v1, they are the same object under a different name.
Vertex &v4 = v1;
// v1.previous_vertex_id is a pointer to v2.
v1.setPrevious(v2);
// v5 is a copy of v2. A different object at a different memory location.
Vertex v5 = v1.getPrevious();
// v6 is a reference to v2, they are the same object under a different name.
Vertex &v6 = v1.getPrevious();
现在,您可以使用getPrevious
作为非指针访问前一个顶点。只是要小心你分配它的方式,所以你只在预期的时候复制它(v5
/v6
的例子(。
只写
Vertex previous_vertex_id;
不要使用*
相关文章:
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型