gpt4 book ai didi

c++ - C++中const成员函数中的静态成员修饰

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:14:41 25 4
gpt4 key购买 nike

我正在处理链表,但无法修改 const 函数“void Print() const”中当前指针的值

在函数 Print 中,我想做 "current= head" 然后像 "current=current->link" 一样递增,但不能这样做,bcz它表明

“错误 C3490:无法修改‘current’,因为它正在通过 const 对象访问 e:\Cpp\projects\data structure ass-1\data structure ass-1\source.cpp 83 1 Data结构 Ass-1"

#include<iostream>

struct node
{
int data;
node *link;
};

class List
{
node *head,*current,*last;
public:
List();
// List(const List&);
// ~List();

void print() const;

};

using namespace std;

int main()
{
List List1;
}

void List::print() const
{
current=head; //here is my error
current=current->link;
}

List::List():current(head)
{

}

最佳答案

如果一个类的成员函数声明为const:

void print() const;

这意味着,这个函数不能修改它的类的数据成员。在你的情况下变量:

node *head,*current,*last;

不能在print() 的主体中修改。因此,您不能更改这些指针指向的地址。解决此问题的一种方法是在 print() 函数中定义一个局部变量 temp。这样的变量可以被修改并完成与 current 应该做的相同的工作:

void List::print() const
{
node *temp;
temp=head;
temp=temp->link;
}

关于c++ - C++中const成员函数中的静态成员修饰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555188/

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