【发布时间】:2021-01-10 11:35:16
【问题描述】:
我已经为此工作了一段时间,目前很困惑。该程序的起始要求是接受一个字符串,为该类创建一个对象,并将其转换为一个字符链表。我遇到了整个类的问题,因为当我尝试在 while 循环之前在 Main 函数中预定义一个新对象时,我收到错误 charchain.cpp:(.text+0x20): undefined reference to linkedChar:: linkedChar() 我已经测试了这个类,并且成功地转换为字符的链接列表。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct node {
char data;
node* next;
};
class linkedChar
{
private:
node* head;
public:
string str;
linkedChar();
linkedChar(const std::string s){
head = NULL;
strToLinkedChar(s);
}
node* add(char data)
{
node* newnode = new node;
newnode->data = data;
newnode->next = NULL;
return newnode;
}
node* strToLinkedChar(string str){
head = add(str[0]);
node* curr = head;
for (int i = 1; i < str.size(); i++) {
curr->next = add(str[i]);
curr = curr->next;
}
}
void print()
{
node* curr = head;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
}
void listLen(){
int counter = 0;
node* curr = head;
while (curr != NULL) {
curr = curr->next;
counter++;
}
std::cout << "There are " << counter << " characters in the current linked list of characters." << std::endl;
}
};
int main()
{
int userInput;
linkedChar linkedObject;
while (userInput != 6){
userInput = -1;
std::cout << "Option Menu: \n1. Enter new string and store as linked list of characters in an ADT LinkedChar class\n2. Get current length (number of characters stored) from the LinkedChar \n3. Find index of character in this LinkedChar \n4. Append another LinkedChar to this LinkedChar (no shallow copy)\n5. Test if another LinkedChar is submatch of this LinkedChar\n6. Quit\n" << std::endl << "Input:";
std::cin >> userInput;
std::cout << std::endl;
if(userInput == 1){
string str;
std::cout << "Enter the string you want to turn into a linked list of characters: ";
std::cin >> str;
std::cout << std::endl;
linkedObject = linkedChar(str);
} else if(userInput == 2){
linkedObject.listLen();
}
}
}
感谢您的任何意见!
【问题讨论】:
标签: c++ class object linked-list nodes