我一直在研究一个使用课程的程序。我知道setter和getter用于访问私有成员,但如果我使用getInput()
在类中输入数据,我还需要setter和getter吗?
#include <iostream>
#include<conio.h>
using namespace std;
void printList();
void delete_end_node();
struct list
{
list *head, *tail;
list *next;
};
class node
{
private:
string name; // Name
int age; // Age in integer
float height; // In meters
public:
node *next; // Pointer to next node
node *head, *tail;
node *start_ptr = NULL; // Start Pointer (root)
node *temp;
node *temp2;
node()
{
head = NULL;
tail = NULL;
}
void printList();
void delete_end_node();
void search();
void getInput()
{
int total;
cout<< "How many you want to input? ";
cin>> total;
for (int i=0; i<total; i++)
{
temp = new node;
cout << "Please enter the name of the person: ";
cin >> temp->name;
cout << "Please enter the age of the person : ";
cin >> temp->age;
cout << "Please enter the height of the person : ";
cin >> temp->height;
temp->next = NULL; // Sets the node to be the last node
if (start_ptr == NULL)
start_ptr = temp;
else
{
temp2 = start_ptr; // We know temp2 is not NULL - list not empty!
while (temp2->next != NULL) // The loop will terminate when temp2
temp2 = temp2->next; // points to the last node in the list
// Move to next link in chain
temp2->next = temp; // Sets the pointer from that last node to point
// to the node that has just declared
}
}
}
//Constructor
node(string node_name, int node_age, float node_height)
{name = node_name; age = node_age; height = node_height;}
// SET
setName(string node_name){name = node_name;}
setAge(int node_age){age = node_age;}
setHeight(float node_height){height = node_height;}
// GET
string getName(){return name;}
int getAge(){return age;}
float getHeight(){return height;}
};
node *start_ptr = NULL; // Start Pointer (root)
int main()
{
node *temp;
node *temp2;
node obj;
int choice;
cout << "MAIN MENU:\n\n1. ADD\n2. DISPLAY\n3. DELETE\n4. EXIT\n";
cin>> choice;
system("cls");
while(choice!=4)
{
switch(choice)
{
case 1:
{
cout<<"ADD"<<endl;
obj.getInput(); // This where it stops
system ("pause");
break;
}
case 2:
{
cout<<"DISPLAY"<<endl;
temp->printList();
system ("pause");
break;
}
case 3:
{
cout<<"Deleting the last node";
temp->delete_end_node();
temp->printList();
//Deleting all the nodes
temp2 = start_ptr; // We know temp2 is not NULL - list not empty!
while (temp2 != NULL)
{
start_ptr = start_ptr->next;
delete temp2; // points to the last node in the list
temp2 = start_ptr;
}
system ("pause");
break;
}
case 4:
{
cout<< "EXIT...";
break;
}
default:
continue;
} // END SWITCH CASE
} //END WHILE
return 0;
} // END MAIN
答案 0 :(得分:2)
你从不需要一个setter和getter。它们是一种常见模式,在Java和C#等解释字节码语言中更常见。
作为一般规则,您通常不会需要它;不要编写你不会使用的代码。
解决代码无法正常工作的过程称为&#34;调试&#34;。您可以在&#34;调试器&#34;中启动您的程序。找到它不起作用的地方,或者一步一步地检查状态。您可以检查程序的状态并尝试发现您不期望的内容,例如指针为空或内存已损坏或未初始化。
Here is a youtube lecture on how to debug a C++ program;它可能有所帮助(我真的用谷歌搜索&#34;如何调试C ++&#34;并链接第一个视频,我希望它不会吮吸)。 Stackoverflow不是为我调试我的程序&#34;服务。