20140408 父类指针指向子类对象 ;delete ;static作用
2014-04-08 20:13
417 查看
1、父类指针可以指向子类对象
静态联翩:如果以父类指针指向派生类对象,那么经由该指针只能访问父类定义的函数动态联编:根据指针实际指向的对象类型确定
2、面试宝典 P110 面试题5
#include<iostream> #include<string> #include<vector> using namespace std; class B { private: int data; public: B() { cout<<"default constructor"<<endl; } ~B() { cout<<"destructed "<<endl; } B(int i):data(i) { cout<<"constructor by parameter"<<data<<endl; } }; B Play(B b) {return b;} int main(int agrc,char* argv[]) { B temp=Play(5);//why? return 0; }
3、delete与delete[]的区别
如果动态创建一个对象数组,用delete只能对数据中的第0个对象元素调用析构函数。其他不对象元素不可能调用。而delete[] 对所有数组中所有对象元素调用析构函数。如果你的数组中对象在创建时,其成员也是动态创建的,则用delete必然内存泄露。4、如何给字符串数组赋值?
用strcpy函数
5、操作符operator错写为operate
6、自己编写string类
//mystring.h class String { public: String (const char *str=NULL);//普通构造函数 String(const String &other);//拷贝构造函数 ~String(void); String & operator=(const String &other); void print(); private: char *m_data;//有动态申请的成员,所以需要自己定义拷贝构造函数和赋值函数 };
//mystring.cpp #include<iostream> #include"mystring.h" using namespace std; String::String(const char *str) { if(str==NULL) { m_data=new char[1]; *m_data='\0'; } else { m_data=new char[strlen(str)+1]; strcpy(m_data,str); } } String::~String(void) { delete [ ] m_data; } String::String(const String &other) { m_data=new char[strlen(other.m_data)+1];//深拷贝 strcpy(m_data,other.m_data); } String & String::operator=(const String &other) { if(this==&other)//这个if很重要。当传入的参数和当前实例(*this)是同一实例(指向同一内存),那么一旦释放自身内存,传入的参数的内存也同时被释放,因此
//再也找不到赋值的内容了!!!!!!! return *this; delete [] m_data; m_data=new char[strlen(other.m_data)+1];//新申请空间,深拷贝 strcpy(m_data,other.m_data); return *this; } void String::print() { cout<<m_data<<endl; }
//test.cpp #include<iostream> #include"mystring.h" using namespace std; void main() { String str("hello"); str.print(); String str1; str1=str; }
7、关键字static三个主要作用
在函数体,一个被声明为静态的变量在这一函数被调用过程中维持其值不变。在模块(如.cpp文件)内(但在函数体外),一个被声明为静态的变量可以被模块内所用函数访问,但不能被模块外其它函数访问。它是一个本地的全局变量。
在模块内,一个被声明为静态的函数只可被这一模块内的其它函数调用。那就是,这个函数被限制在声明它的模块的本地范围内使用。
相关文章推荐
- 转载 a href=#与 a href=javascript:void(0) 的区别
- 简易贪吃蛇V1.2
- 数据导入HBase最常用的三种方式及实践分析
- 【Linux 入门笔记】命令行BASH的基本操作
- 在VS 2010中如何使用Class Wizard添加消息处理函数
- Monkeyrunner学习一
- 开类小说明
- Markdown语法
- Sql还原数据库出现3154错误
- Bean property 'adminService' is not writable or has an invalid setter method
- codeforences 29A
- 中断处理(中断向量寄存器)
- Java 读取文件
- 存储16进制数据的字节数组BYTE与字符串之间的互换
- POJ 3046
- Android Mms专题之:信息发送流程
- 【顺时针打印矩阵】
- C#学习
- C plus plus 控制格式
- 高质量C/C++编程之文件结构