Reputation: 47
I have this class:
#ifndef String_H
#define String_H
class String
{
public:
String();
String(const char*, ...);
String(const String&);
~String();
const String& operator= (const char*);
const int capacity();
void clear(){ string[0] = '\0'; }
const char* getString()const { return string; }
const int lenght()const { return length; }
private:
int length;
char *string;
void alloc(const int);
};
#endif
And in the implementation i have this:
#include <wtypes.h>
#include "String.h"
#include "Log.h"
#include <stdio.h>
String::String()
{
alloc(1);
clear();
}
String::String(const char* _string, ...)
{
//length = 0;
if (_string != NULL)
{
static char buff1[4096];
va_list args;
va_start(args, _string);
int res = vsprintf_s(buff1, 4096, _string, args);
va_end(args);
if (res > 0)
{
alloc(res + 1);
strcpy_s(string, length, buff1);
}
}
else
{
alloc(1);
clear();
}
}
String::String(const String& _string)
{
if (&_string != NULL)
{
alloc(_string.lenght());
strcpy_s(string, length, _string.getString());
}
else
{
alloc(1);
clear();
}
}
String::~String()
{
delete[]string;
}
const String& String::operator= (const char* str)
{
if (strlen(str) > sizeof(string) + 1)
{
delete[] str;
alloc(strlen(str) + 1);
strcpy_s(string, length, str);
}
else
{
strcpy_s(string, length, str);
}
return (*this);
}
void String::alloc(const int size)
{
length = size;
string = new char[size];
}
And when in main I do:
String a;
String b("hi");
a = b;
The compiler says me that:
Error 2 error LNK2019: unresolved external symbol "public: class String const & __thiscall String::operator=(class String const &)" (??4String@@QAEABV0@ABV0@@Z) referenced in function _main C:..\main.obj
AND
Error 3 error LNK1120: 1 unresolved externals C:..\MyLibrary.exe
This is making me crazy. Please help me. I can't see what i'm doing wrong.
Upvotes: 0
Views: 136
Reputation: 35440
This line invokes the assignment operator:
a = b;
You are missing an assignment operator that takes a String
.
This is not the assignment operator that will be called:
const String& String::operator= (const char* str)
A typical assignment operator would have the following signature:
String& String::operator= (const String& s)
Please read up on the "Rule of 3". What is The Rule of Three?
Upvotes: 1