您的位置:首页 > 其它

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文件)内(但在函数体外),一个被声明为静态的变量可以被模块内所用函数访问,但不能被模块外其它函数访问。它是一个本地的全局变量

在模块内,一个被声明为静态的函数只可被这一模块内的其它函数调用。那就是,这个函数被限制在声明它的模块的本地范围内使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: