【发布时间】:2011-04-08 01:27:06
【问题描述】:
我创建了一个 myString 类,我正在尝试运行以下代码:
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
...
};
我的问题:
- 为什么不打印“hello”?
- 为什么
s=k行会导致链接器错误?
这是错误:
链接:c:\users\perry\documents\visual studio 2010\Projects\inheritance\Debug\inheritance.exe 未找到或未构建 通过最后一个增量链接;执行完整链接 1>main.obj:错误 LNK2019:未解析的外部符号“类 std::basic_ostream > & __cdecl 运算符
&,class myString *)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@PAVmyString@@@Z) 在函数“public: class myString & __thiscall”中引用 myString::operator=(class myString &)" (??4myString@@QAEAAV0@AAV0@@Z) 1>c:\用户\佩里\文档\视觉工作室 2010\Projects\inheritance\Debug\inheritance.exe:致命错误 LNK1120: 1 个未解决的外部问题
谢谢, 李
【问题讨论】:
-
我已添加错误消息。感谢您的帮助:)
-
你需要查找三的规则(或者是四)。无论如何,需要一个正确的赋值运算符和复制构造函数(缺少复制构造函数,并且赋值运算符声明不是我所说的标准(并且实现是错误的(在 len 中有一个错误)))。当您使用它时,请查找副本并交换 idium。
标签: c++ operator-overloading operator-keyword