#include <iostream>
#include <cassert>
#include <cstdlib>
using namespace std;
char* my_strcpy(char* dest, char *src)
{
assert(dest != NULL && src != NULL);
char *ret = dest;
while ((*dest++ = *src++)!= '\0');
return ret;
}
int my_len1(const char *mystr) {
// '/0'
int len = 0;
assert(mystr);
while (*(mystr++) != '\0')
{
len++;
}
return len;
}
int my_len2(const char *mystr) {
//递归
assert(mystr);
//递归结束条件
if (*mystr == '\0') {
return 0;
} else {
return (1 + my_len2(++mystr));
}
}
int my_len3(const char* mystr) {
//两个相邻char的地址差是1
assert(mystr);
const char* tmp = NULL;
printf("mystr = %p \n", mystr);
tmp = mystr;
printf(" before tmp = %p\n", tmp);
while (*(tmp) != '\0')
{
tmp++;
};
printf(" after tmp = %p \n", tmp);
return tmp - mystr;
}
class Box {
public:
Box() :m_height(0), m_width(0)
{
cout << "无参构造" << endl;
}
Box(const Box &b):m_height(b.m_height),m_width(b.m_width)
{
cout << "有参构造" << endl;
}
Box(const int h, const int w)
{
this->m_height = h;
this->m_width = w;
cout << "调用了 (int h ,int w)" << endl;
}
Box operator+(const Box &b)
{
this->m_height = this->m_height + b.m_height;
this->m_width = this->m_width + b.m_width;
cout << " 双目 +" << endl;
return *this;
}
Box& operator=(const Box& other)
{
if (this == &other)
{
return *this;
}
cout << "拷贝赋值" << endl;
this->m_height = other.m_height;
this->m_width = other.m_width;
return *this;
}
~Box()
{
cout << "执行析构" << endl;
}
int m_height;
int m_width;
};
class String;
class String
{
public:
char *m_str = NULL;
public:
String() :m_str(NULL) {
cout << "String 无参构造函数" << endl;
};
String(char *str);
String(const String &str);
String& operator=(const String& other);
friend ostream& operator<<(ostream &out, String& s);
~String();
};
ostream& operator<<(ostream& out, String& s) {
cout << "String.m_str:";
out << s.m_str << endl;
return out;
}
String::String(char* str) {
int len = my_len1(str);
this->m_str = new char[len +1];
my_strcpy(this->m_str, str);
}
String::String(const String& str)
{
int len = my_len1(str.m_str);
this->m_str = new char[len + 1];
my_strcpy(this->m_str, str.m_str);
}
String& String::operator=(const String& other) {
if (this == &other) {
return *this;
}
delete[] this->m_str;
int len = my_len1(other.m_str);
this->m_str = new char[len + 1];
my_strcpy(this->m_str, other.m_str);
cout << "拷贝赋值" << endl;
return *this;
}
String::~String() {
if (NULL != m_str) {
delete[] m_str;
}
}
int main(int argc, char** argv) {
#if 0
cout << "init Box b1 b2 b3" << endl;
Box b1(2, 3), b2(3, 2), b3;
b3 = b1 + b2;
#else
char arr[] = "abcd";
cout << my_len1(arr) << endl;
char arr1[] = "1234";
char *res = my_strcpy(arr1, arr);
cout << arr1 << endl;
String s1(arr);
String s2;
s2 = s1;
cout << s2 << endl;
#endif
system("pause");
return 0;
}
记录一次给QQ好友讲解class的构造拷贝构造 拷贝赋值(浅拷贝、深拷贝赋值)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...