You*_*Kim 0 c++ class linked-list self-reference
这是一个简单的代码,我尝试使用自引用类型并同时使用别名.
#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();
}
Run Code Online (Sandbox Code Playgroud)
以上工作正常.但是,我宁愿启动代码,如下所示:
class List {
private:
using pNode = struct node*;
struct node {
int data;
pNode next;
...
Run Code Online (Sandbox Code Playgroud)
我想using pNode = struct node*在struct node定义之前放置,以便我也可以在struct node定义中使用它.我相信如果我不使用类,这种代码风格可以正常工作.
不要在别名中隐藏指针语义.这是我永远落后的一个"永不"的建议.
如果您同意只使用node*您的代码,那么您可以写
struct node {
int data;
node* next;
// ..
};
Run Code Online (Sandbox Code Playgroud)
C++引入了命名类型node有struct node,不像C.所以我们可以使用自然的语法.
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |