gpt4 book ai didi

c++ - 如何在 C++ 类中使用自引用类型和别名

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:28 25 4
gpt4 key购买 nike

这是我尝试使用自引用类型并同时使用别名的简单代码。

#include <iostream>
class List {
private:
struct node {
int data;
struct node* next;

node(const int& d=0, struct node* n=nullptr) {
data = d; next = n;
}
~node() {};
};
using pNode = struct node*;
pNode head;

public:
List();
~List();
void print() const { std::cout << head->data; }
};

List::List() {
head = new node{55};
}

int main() {
List *a = new List;
a->print();
}

上面的这个工作正常。但是,我宁愿按如下所示启动代码:

class List {
private:
using pNode = struct node*;
struct node {
int data;
pNode next;
...

我想在 struct node 定义之前放置 using pNode = struct node* 这样我就可以在 struct node 中使用它定义也是如此。我相信如果我不使用类,这种代码风格也能正常工作。

最佳答案

不要在别名中隐藏指针语义。这是一个“永远不要”的建议,我总是落后。

如果你同意在你的代码中只使用node*,那么你可以这样写

struct node {
int data;
node* next;
// ..
};

与 C 不同,C++ 引入了一个名为 node 的类型,带有 struct node。因此我们可以使用自然语法。

关于c++ - 如何在 C++ 类中使用自引用类型和别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54880068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com