编写操作符重载时遇到的问题:
当我把声明的类函数和实现,分别放在头文件和.cpp文件中,进行编译,出现大量的未定义错误,而且无法调试。
头文件中的声明:
class mystring
{
public:
mystring();
mystring(const char*str);
mystring(const mystring&other);
mystring& operator=(const mystring&other);
mystring& operator=(const char* str);
~mystring();
friend mystring operator+(const mystring& s1, const mystring &s2);
friend ostream& operator<<(ostream& os, const mystring &str);
friend istream& operator>>(istream&is, mystring& str);
private:
char* mystr;
};
运行出现大量的未定义符号错误。
不论怎么调试都不能解决错误。
但是,当我把头文件中的声明移到.cpp时,程序立马能运行。
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class mystring
{
public:
mystring();
mystring(const char*str);
mystring(const mystring&other);
mystring& operator=(const mystring&other);
mystring& operator=(const char* str);
~mystring();
friend mystring operator+(const mystring& s1, const mystring &s2);
friend ostream& operator<<(ostream& os, const mystring &str);
friend istream& operator>>(istream&is, mystring& str);
private:
char* mystr;
};
mystring::mystring()
{
this->mystr = NULL;
}
//赋值构造
mystring::mystring(const char*str )
{
int len = 0;
if (str == NULL)
{
this->mystr = new char[1];
*this->mystr = '\0';
return;
}
len = strlen(str);
this->mystr = new char[len + 1];
strcpy(this->mystr, str);
}
//拷贝构造
mystring::mystring(const mystring&other)
{
int len = strlen(other.mystr);
this->mystr = new char[len + 1];
strcpy(this->mystr, other.mystr);
}
mystring& mystring::operator=(const mystring&other)
{
int len = 0;
if (this == &other)
{
return *this;
}
//删除this->mystr之前的数据
delete[] this->mystr;
this->mystr = NULL;
len = strlen(other.mystr);
this->mystr = new char[len + 1];
strcpy(this->mystr, other.mystr);
return *this;
}
//=操作符重载,和赋值构造的流程一致,只是返回值不同。
mystring& mystring::operator=(const char* str)
{
int len = 0;
if (str = NULL)
{
this->mystr = new char[1];
this->mystr = '\0';
return *this;
}
len = strlen(str);
this->mystr = new char[len + 1];
strcpy(this->mystr, str);
return *this;
}
mystring::~mystring()
{
delete[] this->mystr;
this->mystr = NULL;
}
mystring operator+(const mystring& s1, const mystring &s2)
{
mystring s;
int len = strlen(s1.mystr) + strlen(s2.mystr);
delete[]s.mystr;
s.mystr = new char[len + 1];
strcpy(s.mystr, s1.mystr);
strcat(s.mystr, s2.mystr);
return s;
}
ostream& operator<<(ostream& os, const mystring &str)
{
os << str.mystr;
return os;
}
istream& operator>>(istream& is, mystring& str)
{
char buf[1024] = { 0 };
cin >> buf;
str = buf;
return is;
}
int main(void)
{
mystring a("abcd");
cout << a << endl;
system("pause");
return 0;
}
运行结果:
通过在网上查找了解到:现阶段各编译器对模板类的分离式编译支持都不行,要么都写头文件里,要么不要用模板
浙公网安备 33010602011771号