I wrote a simple program that uses a class with a constructor, a destructor and a data member. When I tried to initialize an object, the debugger told me that there was not a destuctor and a destructor.I tried it in Clion, VS2019 and VSCode. And I got the same result like 4). I don't know it occurs all the time when I have actually created the constructor and destructor.
Pls help me. THANKS!
1) String.h
#ifndef TEST_STRING_H
#define TEST_STRING_H
class String {
public:
explicit String(const char *cstr = nullptr);
String(const String &str);
String &operator=(const String &str);
~String();
char *get_c_str() const { return m_data; }
private:
char *m_data;
};
#endif // TEST_STRING_H
2) String.cpp
#include "String.h"
#include <cstring>
inline String::String(const char *cstr) {
if (cstr) {
m_data = new char[strlen(cstr) + 1];
strcpy(m_data, cstr);
} else {
m_data = new char[1];
*m_data = '\0';
}
}
inline String::~String() { delete[] m_data; }
inline String &String::operator=(const String &str) {
if (this == &str)
return *this;
delete[] m_data;
m_data = new char[strlen(str.m_data) + 1];
strcpy(m_data, str.m_data);
return *this;
}
inline String::String(const String &str) {
m_data = new char[strlen(str.m_data) + 1];
strcpy(m_data, str.m_data);
}
3) main.cpp
#include <iostream>
#include "String.h"
using namespace std;
int main() {
String s1("hello");
return 0;
}
4) The result
/tmp/ccCIK0hs.o: In function `main':
/home/Projects/test/main.cpp:7: undefined reference to `String::String(char const*)'
/home/Projects/test/main.cpp:7: undefined reference to `String::~String()'
collect2: error: ld returned 1 exit status