头文件
#pragma once
class TestString
{
public:
TestString(void);
~TestString(void);
public:
TestString(const char * str = NULL);
TestString(const TestString &other);
TestString &operator = (const TestString &other);
private:
char *m_data;
};
实现文件
#include "StdAfx.h"
#include "TestString.h"
#include <string.h>
TestString::TestString(void)
{
}
TestString::~TestString(void)
{
delete []m_data;
}
TestString::TestString(const char * str)
{
if (str == NULL)
{
m_data = new char[1];
m_data = "";
}
else
{
m_data = new char[strlen(str) + 1];
strcpy_s(m_data, strlen(str) + 1, str);
}
}
TestString::TestString(const TestString &other)
{
m_data = new char[strlen(other.m_data) + 1];
strcpy_s(m_data, strlen(other.m_data) + 1, other.m_data);
}
TestString & TestString::operator = (const TestString &other)
{
/自赋值
if (this == &other)
{
return *this;
}
delete []m_data;
m_data = new char[strlen(other.m_data) + 1];
strcpy_s(m_data, strlen(other.m_data) + 1, other.m_data);
return *this;
}
调用测试
char sztest[] = "abcd";
char sztest2[] = "abcde";
TestString str(sztest);
TestString str2(sztest2);
TestString str3(void); //这里有警告,未调用原型函数(是否是有意用变量定义的?)
str2 = sztest;
str3 = sztest; //错误,表达式必须是可修改的左值
当把str3 = sztest;注释,依然会有警告
1.指定了多个默认构造函数
2.未调用原型函数(是否是有意用变量定义的?)
对于第二点警告:TestString str3(void);编译无法识别调用的是TestString(void)与TestString(const char * str = NULL)
对于第一点警告:TestString(void);和TestString(const char * str = NULL);是否等同