20140408 父类指针指向子类对象 ;delete ;static作用

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

转载于:https://www.cnblogs.com/yexuannan/p/3652782.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值