0

Basically I encountered a few problems when I was fiddling with designing a basic singly linked list. Here are the declarations

struct Node {
  int val;
  Node* next;
};

struct SinglyLinkedlist {
  int size;
  Node* head;
  SinglyLinkedlist();

  const Node* Begin() const {
    printf("const begin\n");
    if (size > 0)
      return head->next;
  }

  Node* Begin() {
    printf("begin\n");
    if (size > 0)
      return head->next;
  }
};

I've seen in STL containers, e.g std::queue, that functions with the same name could co-exist like this,

//std::queue
value_type& front();
const value_type& front() const;

it caught me by surprise because it didn't trigger compilation failure like function redefinition e.g functions with the same name, nor did it form a function overloading, e.g function with same names but with different argument types. Therefore, I was wondering if this is a kind of function overloading I didn't know of or some other sorts? and how does the program know which Begin() to call during run-time, I am guessing the compiler would detect the CONSTNESS in the context and decide which to call? The other problem I was having was that without explicitly overloading * operator, *Begin() e.g Node* is dereferenced and print out the val value, basically the same as Begin()->val, I wonder if * operator should function this way.Thank you very much.

int main()
 {
  SinglyLinkedlist l;
  l.Push(1);
  l.Push(2);
  l.Push(3);

  l.PrintList();
  printf("%d\n",*l.Begin()); //print out 1 same as l.Begin()->val
}
4

4 回答 4

1

是的,引用和常量引用是两种不同的类型。编译器将根据上下文选择 const 声明。

取消引用 Node* 会为您提供一个结构节点,并且您的 printf 中的 %d 正在获取四个字节(在大多数编译器中)并将其视为一个 int。如果你要改变结构中成员的顺序,它会改变你的输出。

于 2013-10-17T05:09:45.097 回答
0

关于您的const Node* Begin() const方法,请参阅此问题

本质上,该方法保证了对象不会发生变异,因此可以在常量实例上调用。

所以理论上,这应该有效:

int main( ) {
    SinglyLinkedList lst;
    const SinglyLinkedList clst;

    lst.Push(1);
    lst.Push(2);
    clst.Push(3);
}

这是自相矛盾的,因为结果是列表的突变。但是,修改是针对 的Nodes,而不是实际的SinglyLinkedList.

关于*operator:它工作正常。仅对象没有特殊行为。

于 2013-10-17T05:08:18.340 回答
0

在 C++ 中,你不能基于返回类型重载,但你可以重载 cv 限定符:

有关参与重载决议 (13.3) 的函数的信息:其参数类型列表 (8.3.5),如果函数是类成员,则函数本身和类的 cv 限定符(如果有)其中声明了成员函数。[...]

Cv 限定符const,volatilemutable.

因此,虽然您的两个函数都具有相同的返回类型 ( Node*),但它们的 cv 限定符是不同的,因此允许重载。

于 2013-10-17T05:09:20.147 回答
0

您需要阅读有关 const 函数重载的信息。常量和非常量函数彼此不同。例如,如果您尝试在有时需要 const 类型和有时需要非 const 类型的不同地方使用它,那么您需要这两个函数,这样它就不会抛出错误。

看这个例子:链接

于 2013-10-17T05:10:02.787 回答