gpt4 book ai didi

c++ - 对 C++ 中的类::函数的 undefined reference

转载 作者:行者123 更新时间:2023-11-28 00:34:39 26 4
gpt4 key购买 nike

<分区>

在编写一个程序时,我们必须为堆栈构建一个类,并使用它来检查字符串是否为回文。编译器提示对类 Stack 中的成员函数的 undefined reference 。我不确定我做错了什么,因为我相信我使用的语法与过去完全相同。该类的文件是 Stack02.h、Stack02.cpp,p02.cpp 是程序的主文件。

来自 Stack02.h

    class Stack 
{
int size;
int tos;
char* S;

public:
Stack(int sz=100); //Constructor
~Stack(); //Deconstructor
bool isFull(void);
bool isEmpty(void);
void Push(char v);
char Pop(void);
};

来自 Stack02.cpp:

    #include "Stack02.h"
using namespace std;

//Exception handling for stacks
struct StackException
{
StackException{char* m}
{
cout << endl << "I am the Stack and I am " << m << "." << endl;
}
};

Stack::Stack(int sz):size(sz),tos(-1){S= new char[size]}; //Constructor
Stack::~Stack(){if(S) delete[] S;} //Deconstructor

bool Stack::isFull(void)
{
return tos >= size - 1;
} //Is the stack full?

bool Stack::isEmpty(void)
{
return tos < 0;
}

void Stack::Push(char v)
{
if(isFull) throw StackException("full");
S[++tos] = c;
}

char Stack::Pop(void)
{
if(isEmpty) throw StackException("empty");
return S[tos--];
}

编译器在 p02.cpp 中提示的函数:

    bool IsPalindrome(string& c) 
{
Stack s;
for (int a = 0; a < c.length(); a++) s.Push(c[a]);

for (int a = 0; !s.isEmpty() ;a < c.length())
{
if (c[a] !=s.Pop()) return false;
}

//can use default return value to check how output looks.
}

生成文件:

    #------------------------------------------------
#Object files
#------------------------------------------------
obj = p02.o Stack02.o
#------------------------------------------------
#Link object files into executable file p02
#------------------------------------------------
p02: ${obj}
g++ -o p02 ${obj} -lm
#------------------------------------------------
#Compile p02.cpp that exercises class Stack
#------------------------------------------------
p02.o p02.cpp Stack02.h
g++ -g -c p02.cpp
#------------------------------------------------
#Compile Stack02.cpp that implements class Stack
#------------------------------------------------
Stack02.o Stack02.cpp Stack02.h
g++ -g -c Stack02.cpp

编译器的提示:

tt054@cs:~$ make p02
g++ p02.cpp -o p02
/tmp/ccYDuT0W.o: In function `IsPalindrome(std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
p02.cpp:(.text+0x1c): undefined reference to `Stack::Stack(int)'
p02.cpp:(.text+0x4e): undefined reference to `Stack::Push(char)'
p02.cpp:(.text+0x9b): undefined reference to `Stack::Pop()'
p02.cpp:(.text+0xc9): undefined reference to `Stack::isEmpty()'
p02.cpp:(.text+0xe1): undefined reference to `Stack::~Stack()'
p02.cpp:(.text+0xfc): undefined reference to `Stack::~Stack()'
collect2: ld returned 1 exit status
make: *** [p02] Error 1

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com