1。常量对常量函数:
#include"stdafx.h"
#include <iostream>
using namespace std;
class Base ...{
int m_cc; int m_dd;
public:
Base() ...{
m_cc=0; m_dd=0; cout << "Base constructor" << endl;
} 
~Base() ...{ cout << "Base destructor" << endl; }
int getcc() const ...{ return m_cc; }; //函数1
int getcc() ...{ return m_cc; }; //函数2
Base* operator&() ...{ return this; };//算子1
const Base * operator&() const ...{ return this; }; //算子2
};
const Base * pd1;
int main()
...{
Base dd1;
const Base dd5;
Base * pd2=&dd1; ;//算子1
const Base * pd3=&dd1; ;//算子1
pd1=&dd5; ;//算子2
cout<<pd1->getcc()<<endl; //函数1
Base xx=dd1;
cout<<xx.getcc()<<endl; //函数2
return 0;
}
2.赋值函数注意的四个步骤:
class String
...{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
~ String(void); // 析构函数
String & operate =(const String &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
String::String(const char *str)
...{
if(str==NULL)
...{
m_data = new char[1];
*m_data = ‘0’;
}
else
...{
int length = strlen(str);
m_data = new char[length+1];
strcpy(m_data, str);
}
}
// String的析构函数
String::~String(void)
...{
delete [] m_data;
// 由于m_data是内部数据类型,也可以写成 delete m_data;
}
// 拷贝构造函数
String::String(const String &other)
...{
// 允许操作other的私有成员m_data
int length = strlen(other.m_data);
m_data = new char[length+1];
strcpy(m_data, other.m_data);
}
// 赋值函数
String & String::operate =(const String &other)
...{
// (1) 检查自赋值
if(this == &other)
return *this;
// (2) 释放原有的内存资源
delete [] m_data;
// (3)分配新的内存资源,并复制内容
int length = strlen(other.m_data);
m_data = new char[length+1];
strcpy(m_data, other.m_data);
// (4)返回本对象的引用
return *this;
}
类String拷贝构造函数与普通构造函数的区别是:在函数入口处无需与NULL进行比较,这是因为“引用”不可能是NULL,而“指针”可以为NULL。
(1)第一步,检查自赋值。你可能会认为多此一举,难道有人会愚蠢到写出 a = a 这样的自赋值语句的确不会。但是间接的自赋值仍有可能出现
(2)第二步,用delete释放原有的内存资源。如果现在不释放,以后就没机会了,将造成内存泄露。
(3)第三步,分配新的内存资源,并复制字符串。注意函数strlen返回的是有效字符串长度,不包含结束符‘/0’。函数strcpy则连‘/0’一起复制。
(4)第四步,返回本对象的引用,目的是为了实现象 a = b = c 这样的链式表达。注意不要将 return *this 错写成 return this 。那么能否写成return other 呢?效果不是一样吗?
不可以!因为我们不知道参数other的生命期。有可能other是个临时对象,在赋值结束后它马上消失,那么return other返回的将是垃圾。
3.函数隐藏。
#include<iostream>
using namespace std;

class B ...{
public:
int f(int i) ...{ cout << "f(int): "; return i+1; }
// ...
};

class D : public B ...{
public:
// using B::f; 试试注释掉和不注释掉的差别。 
double f(double d) ...{ cout << "f(double): "; return d+1.3; }
// ...
};
int main()
...{
D* pd = new D;
cout << pd->f(2) << ' ';
cout << pd->f(2.3) << ' ';
}
未完再续。。。
4356

被折叠的 条评论
为什么被折叠?



