不能再两次被石头绊倒了,把自己不会的记录下来吧。
1.一道是对齐的题目。
// 结构体对齐.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
struct test1 {
short x; //2
short y; //2
};
struct test2 {
long x; //4
short y; //2+2
};
struct test3 {
char x; //1+1
short y; //2
};
struct test4 {
char x; //1+1
short y; //2
long z; //4
};
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d\n", sizeof(test1)); //输出4
printf("%d\n", sizeof(test2)); //输出8
printf("%d\n", sizeof(test3)); //输出4
printf("%d\n", sizeof(test4)); //输出8
return 0;
}
2. ifndef/define/endif的作用
主要目的是防止头文件的重复包含和编译,
3. 实现String类的构造,析构,赋值函数
这道题是剑指offer里面的第一题,为什么在当时做不出来呢?学得不好啊。。。。
// 实现String类.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
class String {
public:
String(char *str = NULL);
~String(void);
String(const String& other);
String& operator=(String& other);
//工具函数
void PrintStr()
{
cout << m_pdata << endl;
}
private:
char* m_pdata;
};
String::String(char *str)
{
if(str == NULL) {
m_pdata = new char[1];
m_pdata[0] = '\0';
} else {
m_pdata = new char[strlen(str)+1];
strcpy(m_pdata, str);
}
}
String::~String()
{
if(m_pdata != NULL)
delete m_pdata;
}
String::String(const String& other)
{
m_pdata = new char[strlen(other.m_pdata)+1];
strcpy(m_pdata, other.m_pdata );
}
String& String::operator=(String& other)
{
/*if(this == &other)
return *this;
delete[] m_pdata; //这个东西[]又忘了
m_pdata = new char[strlen(other.m_pdata)+1];
strcpy(m_pdata, other.m_pdata);
return *this;*/
if (this != &other)
{
String tmp(other); //tmp是局部变量,之后会自动释放
char *pTmp = tmp.m_pdata;
tmp.m_pdata = m_pdata;
m_pdata = pTmp;
}
return *this;
}
int _tmain(int argc, _TCHAR* argv[])
{
String str1("abcd");
String str2("cd");;
String str3 = str1;
str3.PrintStr();
str3 = str3 = str2;
str3.PrintStr();
return 0;
}
4.走迷宫的答题