I’ve created a class myString and I’m trying to run the following code:
class myString{
char* str;
int len;
public:
myString(char* str1 = " "){
len = strlen(str1);
str = new char[len+1];
strcpy(str, str1);
};
int getLen() const {
return len;
};
char* getString() const {
return str;
};
~myString(){
delete[] str;
};
myString& operator=(myString& orig){
cout << "hello";
if (str == NULL){
delete[] str;
};
str = new char[orig.getLen()];
strcpy(str, orig.getString());
cout << this << endl;
return *this;
};
...
};
int main(){
myString s("bla");
myString k("dingo");
myString g = s;
// s=k; //When this line is commented I get a linking error
...
};
My Questions:
- Why “hello” does not get printed?
- Why the line
s=kcauses a linker error?
This is the error:
LINK : c:\users\perry\documents\visual studio
2010\Projects\inheritance\Debug\inheritance.exe not found or not built
by the last incremental link; performing full link 1>main.obj : error
LNK2019: unresolved external symbol “class
std::basic_ostream > & __cdecl
operator<<(class std::basic_ostream&,class myString *)” (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@PAVmyString@@@Z)
referenced in function “public: class myString & __thiscall
myString::operator=(class myString &)” (??4myString@@QAEAAV0@AAV0@@Z)
1>c:\users\perry\documents\visual studio
2010\Projects\inheritance\Debug\inheritance.exe : fatal error LNK1120:
1 unresolved externals
Thanks,
Li
For the following, you need a copy constructor. It does not use the assignment operator function.
Edit
For the linker error – I can’t help you with that. Rather than guessing at what
operator<<that line calls, I will just give up on this because you haven’t provided the code. In normal C++ code, there is no way that a simplecout << this;would cause a linker error.couthas an operator that accepts avoid const*for this. You have declared an operator somewhere that provides a better match but did not define it.