4

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

在函数打印中,我想做“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 Structure 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)
{

}
4

6 回答 6

4

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

void print() const;

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

node *head,*current,*last;

不能在 的正文中修改print()。因此,您无法更改这些指针指向的地址。解决这个问题的一种方法是temp在你的print()函数中定义一个局部变量。可以修改这样的变量并执行与current预期相同的工作:

void List::print() const
{
    node *temp;     
    temp=head;   
    temp=temp->link;
}
于 2013-09-01T07:55:45.743 回答
3

当您声明一个const成员函数时,this指针在为对象调用时变为函数const内部。const

这意味着const成员函数可以防止对类的数据成员进行任何直接或间接的修改。

直接暗示就像您在程序中所做的那样(直接在const成员函数中修改数据成员,这违反了它的目的)。除非您不修改它们,否则可以执行任何涉及数据成员的操作。此外,您可以在成员函数中调用其他const成员const函数。

而间接意味着您甚至不能调用non-const该类的其他成员函数,因为它们可能会修改数据成员。

const当您只想获取/读取值时,通常会使用成员函数。因此,在您的情况下,您不应该使用const成员函数。

此外,您可以调用对象non-constconst成员函数non-const

于 2013-09-01T04:46:27.983 回答
2

您将 print() 函数声明为 const。这意味着该函数不会修改类的成员变量,但这是您在函数定义中要做的第一件事。

于 2013-09-01T04:25:06.543 回答
1

修改node *head,*current,*last;mutable node *head,*current,*last;

于 2013-09-01T06:59:26.033 回答
0

该错误准确地告诉您正在发生的事情 - 当您说 时List::print() const,您承诺不会修改列表中的任何成员。但后来你去尝试修改current.

没有看到其余代码很难说,但也许current不应该是成员变量,并且应该是List::print(). 或者也许List::print()不应该是 const。你也可以使current可变的,但这几乎总是不好的做法。

于 2013-09-01T04:25:13.780 回答
0

声明current为方法 print 的局部变量。如果您将current其用作其他用途的成员变量,则局部变量将隐藏它。如果您不用current作成员变量,则可以将其删除。

于 2013-09-01T04:28:26.597 回答