基本上我在设计一个基本的单向链表时,遇到了一些问题。 这里有C++函数重载
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;
}
};
我在STL容器中看到的声明,如性病::队列,即具有相同名称的功能可以共存这样,
//std::queue
value_type& front();
const value_type& front() const;
它抓住我因为它没有像函数重定义那样触发编译失败,例如具有相同名称的函数,也没有形成函数重载,例如具有相同名称但具有不同参数类型的函数。因此,我想知道这是否是一种函数重载,我不知道或者其他类型?以及程序如何知道在运行期间调用哪个Begin(),我猜测编译器会在上下文中检测CONSTNESS并决定调用哪个? 我遇到的另一个问题是,如果没有显式重载*运算符,* Begin()例如Node *被取消引用并打印val值,基本上与Begin() - > val一样,我想知道*运算符是否应该运行非常感谢。
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
}
你是绝对正确的,如果我改变VAL类型为double,最后的printf(%d)会给我垃圾值!谢谢 –