20140408 父类指针指向子类对象 ;delete ;static作用
2024-08-30 17:00:00
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文件)内(但在函数体外),一个被声明为静态的变量可以被模块内所用函数访问,但不能被模块外其它函数访问。它是一个本地的全局变量。
- 在模块内,一个被声明为静态的函数只可被这一模块内的其它函数调用。那就是,这个函数被限制在声明它的模块的本地范围内使用。
最新文章
- 以项目谈WebGIS中Web制图的设计和实现
- Bootstrap3系列:按钮式下拉菜单
- WEB 用户指南 -- WEB 系统结构文档
- 数据仓库之SSIS开发
- com.opensymphony.xwork2.ognl.OgnlValueStack] - target is null for setProperty(null, ";emailTypeNo";, [Ljava.lang.String;@6f205e]
- angular测试-Karma + Jasmine配置
- 使用Microsoft Fakes进行单元测试(2)
- 阿里云的NoSQL存储服务OTS的应用分析
- js 变量提升+方法提升
- 高级软件工程2017第5次作业—— 团队项目:需求改进&;系统设计
- C语言--指针函数和函数指针
- Linux新手随手笔记1.3
- python yield,yield from,深浅拷贝
- python学习1-1
- KVM+QEMU虚拟化概念
- 菜鸟帮你跳过openstack配置过程中的坑[文末新添加福利]
- 四)Spring + Quartz
- 网络文件系统nfs在ubuntu16.04的安装
- eclipse开发文档模板
- .net 4.5如何使用Async和Await进行异步编程
热门文章
- 出现Warning: date(): It is not safe to rely on the system&#39;s timezone settings的解决办法
- noip历年试题
- 随机生成一串字符串(java)
- AcWing 204. 表达整数的奇怪方式 (线性同余方程组)打卡
- CCC2018 最大战略储备
- qemu源码分析
- Red Hat Enterprise Linux 7.7 使用最小化安装后,怎么安装桌面的解决方法
- hdu 6435 /// 状压
- yum处理损坏的包依赖关系
- ssh隧道实现端口转发