【发布时间】:2020-07-08 02:36:21
【问题描述】:
以下是发送给我的帮助代码示例。我确实了解了一些事情,尽管我现在不确定是否应该为我创建的每个变量设置 setter 和 getter?
我正在开发的程序有很多变量,因为它是一个存储信息和东西的程序。如果不是太多,是否有人可以简化它?如果在这种状态下是不可能的,那也没关系。
#include<iostream>
#include<string>
using namespace std;
//This is the class to be used
//as a node in the linked list.
class Node
{
//this are private members,
//since they are declared as private
//they can only be accessed by this class
//which will ensure data security :) (this is called encapsulation)
private:
int id;
string name;
Node *next;
//This are public member functions
//These functions are the only way to access
//the data members of the Node class
public:
//These function are called setter/mutators
void setId(int);//this function will set the id data member
void setName(string);//this function will set the name data member
void setNext(Node*);//this function will set the next pointer
//These functions are called getters/accessors
int getId();//this function will get/return the value of the id data member
string getName();//this function will get/return the value of the name data member
Node* getNext();//this function will get/return the address of the next node
}*head = NULL, *tail = NULL;
//This function will traverse the linked list.
//It is placed outside the class because it is not needed
//to be one of the class function members
void traverse(Node*);
int main()
{
char response = 'y';
//variable declarations for inputs
int inputData;
string inputName;
while(response == 'y')//this will loop the input phase
{
system("cls");
cout<<"Enter ID: ";
cin>>inputData;
cin.ignore();
cout<<"Enter name: ";
getline(cin,inputName);
//Note about the dot (.) operator and the arrow (->)
//operator: the dot operator is used when accessing
//structure or class members without using a pointer,
//while the arrow operator is used to access structure
//or class members when using pointers
Node *node = new Node;
node->setId(inputData);//calls the setId member function
node->setName(inputName);//calls the setName member function
node->setNext(NULL);//calls the setNext member function
if(head==NULL)
{
head = node;
}
if(tail==NULL)
{
tail = node;
}
else
{
tail->setNext(node);
tail = node;
}
cout<<"Enter another?: ";
cin>>response;
}
traverse(head);
return 0;
}
//Here are the function members definitions
void Node::setId(int id)
{
this->id = id;
}
void Node::setName(string name)
{
this->name = name;
}
void Node::setNext(Node *next)
{
this->next = next;
}
int Node::getId()
{
return this->id;
}
string Node::getName()
{
return this->name;
}
Node* Node::getNext()
{
return this->next;
}
//This is the function definition of the traverse function
void traverse(Node *node)
{
system("cls");
while(node != NULL)
{
cout<<"ID: "<<node->getId()<<endl;
cout<<"Name: "<<node->getName()<<endl<<endl;
node = node->getNext();
}
}
【问题讨论】:
-
内部链表或外部ie。标准::列表。
标签: c++ class oop linked-list