zoukankan      html  css  js  c++  java
  • 构造函数,const char*与c_str

     1 /*******************************************************************************
     2 * 版权所有:
     3 * 模 块 名:
     4 * 文 件 名:class_default_constructor_for_const_member.cpp
     5 * 实现功能:
     6 * 作    者:XYZ
     7 * 版    本:V1.0
     8 * 日    期:2013.08.12
     9 * 其他说明:xiao13149920@foxmail.com
    10 ********************************************************************************/
    11 // class_default_constructor_for_const_member.cpp
    12 #include<iostream>
    13 #include<cstdlib>
    14 #include<cstring>
    15 using namespace std;
    16 
    17 //#define INIT 
    18 
    19 class CBase
    20 {
    21     private:
    22 #ifdef INIT
    23         const int m_const_i;
    24 #endif
    25         static int m_static_i;
    26         const static int m_const_static_i /*= 100*/;
    27 
    28     public:
    29         void print();
    30 };
    31 
    32 int CBase::m_static_i = 10;
    33 const int CBase::m_const_static_i = 100;
    34 
    35 void CBase::print()
    36 {
    37 #ifdef INIT
    38     cout<<"ci="<<ci<<endl;
    39 #endif
    40     cout<<"m_static_i="<<m_static_i<<endl;
    41     cout<<"m_const_static_i="<<m_const_static_i<<endl;
    42 }
    43 
    44 class B
    45 {
    46     private:
    47 #ifdef INIT
    48         CBase& cb;
    49 #endif
    50 };
    51 
    52 int main()
    53 {
    54     // test for default constructor
    55     CBase cb;
    56     cb.print();
    57     B b;
    58 
    59     // test for const char * p = str._cstr();
    60     string str = "hello world";
    61     const char * p = str.c_str();
    62     str[0]='H';
    63     str.append("-----------------
    ");
    64     char parr[128];
    65     memset(parr, 0, sizeof(parr));
    66     strcpy(parr, p);
    67     cout<<"p="<<p<<endl;
    68     cout<<"str="<<str<<endl;
    69     cout<<"parr="<<parr<<endl;
    70 
    71     return 0;
    72 }

    1. 编译器会为每个类自动生成一个缺省的构造函数,拷贝构造,赋值函数. 但有const 数据成员(无static组合的), 引用数据成员是一个例外.即代码中的55,57行. 

    2. 不可把string.c_str()的内容赋值给const char* p, 即代码中的61行

    3. const static 数据成员也可以在类中初始化. 如行26.

    4. 新增若是基类的拷贝构造或者复制函数为私有函数, 那么编译器也不会为派生类生成一个缺省拷贝构造和赋值函数

  • 相关阅读:
    java集合
    移动web页面给用户发送邮件的方法
    如何用CSS和jQuery实现一个侧滑导航菜单
    基于jq的表单填充
    使用JS代码实现点击按钮下载文件
    变量,作用域和内存问题
    如何实现单行/多行文本溢出的省略(...)
    CSS中浮动和定位对元素宽度/外边距/其他元素所占空间的影响
    【javascript】函数中的this的四种绑定形式
    前端开发利器webStorm
  • 原文地址:https://www.cnblogs.com/xiao13149920yanyan/p/3252761.html
Copyright © 2011-2022 走看看