阅读《C++Primer》边看边敲代码

这个自己参加第一个成功上线的手游的时候看的一本关于C++比较基础的数据,当时的手游项目也是用C++写的。也是C++的入门书记吧,记得差不多实在2014.9时候看的。在边看这种语法类书的时候边看边敲代码是一个很不错的习惯。现在回忆起来当时也就那么点东西,当时感觉挺多的

------------------------------------------------------------   .h ------------------------------------------------------------

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__


#include "cocos2d.h"


#include <iostream.h>


class HelloWorld : public cocos2d::CCLayer
{
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();  


    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();
    
    // a selector callback
    void menuCloseCallback(CCObject* pSender);
    
    void mhy(int a=1);
    void* myzhizhen();
    void test1(int &ab);
    HelloWorld& operator+=(const HelloWorld& test);
    
    
    void digui(int a);
    
    friend void f_f(HelloWorld& tes);
    const int& consttest(const int& b) const;
 
    std::vector<int>& mydudada();
    CC_SYNTHESIZE(int, m_nID,_nID);
    CC_SYNTHESIZE_PASS_BY_REF(int,D,_d);
    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);
 private:
    int duone;
    int dutwo;
    int duthree;
    
};


class father
{
    int e;
    int r;
    int b;
public:
     father();
//     ~father();
protected:
    int fatherprotec;
};
class child:public father
{
    int e;
    int r;
    int s;
public:
    child();
//    ~child();
    child(int a);
    void mychild(int a);
    
public:
    int cao;
};




//纯虚函数
class student
{
    int a;
    int b;
public:
    virtual void myvirt()=0;
};
class smallstudent
{


public:
    void myvirt(){int a=3;};
};
//多重继承
class a
{
public:
    a(){ int a; a=10;};
};
class b
{
public:
   b(){ int b; b=10;};
};
class c:public a,public b
{
public:
    c();
};






class B1
{
public:
    B1(int i)
    {
        b1 = i;
        cout<<"构造函数 B1."<<i<< endl;
    }
    void print()
    {
        cout<<"B1.print()"<<b1<<endl;
    }
private:
    int b1;
};


class B2
{
public:
    B2(int i)
    {
        b2 = i;
        cout<<"构造函数 B2."<<i<< endl;
    }
    void print()
    {
        cout<<"B2.print()"<<b2<<endl;
    }
private:
    int b2;
};
class B3
{
public:
    B3(int i)
    {
        b3 = i;
        cout<<"构造函数 B3."<<i<<endl;
    }
    int getb3()
    {
        return b3;
    }
private:
    int b3;
};
class ABC : public B2, public B1
{
public:
    ABC(int i, int j, int k, int l):B1(i), B2(j) , bb(k)//对基类构造函数初始化


    {
        a = l;
        cout<<"构造函数 ABC."<<a<<endl;
    }
    void print()
    {
        B2::print();
        B1::print();
        
//       cout<<"ABC.print()"<<a<<","<<bb.getb3()<<endl;
    }
private:
    int a;
    B3 bb;
};




class ob
{
public:
    void vpuba1()
    {CCLOG("pua1");
    CCLOG("inpro1=%d",inpro1);
    CCLOG("inpri1=%d",inpri1);};
    int inpuba1;
protected:
    void vproa1(){CCLOG("proa1");};
    int inpro1;
private:
    void vpria1(){CCLOG("proa1");};
    int inpri1;
};
class obpub :public ob
{


};
class obpro :protected ob
{
    
};
class obpri :private ob
{
    
};






#endif // __HELLOWORLD_SCENE_H__


------------------------------------------------------------   .cpp ------------------------------------------------------------

#include "HelloWorldScene.h"
#include "AppMacros.h"


USING_NS_CC;


#include<string>
#include<vector>
#include<map>
#include<valarray>
using namespace std;


#include<fstream>
#include<iostream>
#include <iomanip>
#include "abc.h"




//函数模版的使用
template <typename type>


void fun(const type &a,const int &b)
{
    CCLog("%d",b);
}


//类模版的使用
template <typename numtype> //声明一个模板,虚拟类型名为numtype
class myCompare //类模板名为myCompare
{
    public :
    myCompare(numtype a,numtype b)
    {
        x=a;y=b;
    }
    numtype max( )
    {
        return (x>y)?x:y;
    }
    numtype min( )
    {
        return (x<y)?x:y;
    }
    private :
    numtype x,y;
};
//类模版的使用多个通用类型
template <typename T,typename TT,int a>
class Pals
{
private:
    TT sd;
    T  iooek;
    
};
class CBase { };
class CDerived: public CBase { };
class AA {};
class BB {};


enum  myenum
{
    MYMESSAGE_ONE,
    MYMESSAGE_TWO,
    MYMESSAGE_HTREE,
    MYMESSAGE_FOUR,
    MYMESSAGE_FIVE,
    MYMESSAGE_SIX
};
typedef struct tpdest
{
    int a;
}defmysutrct;
typedef struct dugaodatype
{
    int ds;
}duds;


//嵌套类   几乎不用
class A
{
public:
//    static int a;
    class A1
    {
        void output()
        {
            CCLOG("qiantaolei");
        }
    };
    
};


CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();


    // add layer as a child to scene
    scene->addChild(layer);


    // return the scene
    return scene;
}


// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();


    /
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.


    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(HelloWorld::menuCloseCallback));
    
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
                                origin.y + pCloseItem->getContentSize().height/2));


    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition(CCPointZero);
    this->addChild(pMenu, 1);


    /
    // 3. add your codes below...


    // add a label shows "Hello World"
    // create and initialize a label
    
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", TITLE_FONT_SIZE);
    
    // position the label on the center of the screen
    pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - pLabel->getContentSize().height));


    // add the label as a child to this layer
    this->addChild(pLabel, 1);


    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");


    // position the sprite on the center of the screen
    pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));


    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);
    
//    
//    CCLog("123");
    
  
    
    
    duone=0;
    dutwo=0;
    duthree=0;
    
    char ab;
    ab='d';


  
    //测试字符大小
    double d;
    int a;
    a=7;
    a=INT16_MAX;
    CCLog("a=%d",sizeof(a));
    
    //函数模版
    fun(d,a);
    
   
    
    
    //处理数据
    unsigned short unshort;
    unsigned int unint;
    unsigned long unlong;
    
    short myshort;
    myshort=30000;//如果myshort超出-32768到32767,myshort的值就会乱
    unshort=50000;//unsigned short的范伟是32768+32767
    CCLog("myshort=%d",myshort);
    CCLog("unshort=%d",unshort);
    
    // const限定符
    const int dddd=10;
  //3.3浮点数,3.3.1书写浮点数
     // 8.33E5      E5表示10的5次方
    
    
    //浮点类型
    float myfloat;
    myfloat=10.0/3.0;
    CCLog("myfloat=%0.2f",myfloat);//保留到小数点后面2位
    CCLog("myfloat=%f",myfloat);
    
    //3.4  c++算术操作符
    int test1=10;
    int test2=4;
    CCLog("test1+test2=%d",test1+test2);
    int test3;
    int test4;
    test3=10/3;
    test4=10%3;
    CCLog("test4=%d",test4);
    
    //数据强制类型转换
    float test5;
    test5=(float)test1;
    CCLog("test5=%f",test5);
    
    
//4.复合类型
    //4.1数组
    int cards[4]={1,2,3,4};
    cards[0];
    cards[1];
    cards[2];
    cards[3];
    CCLog("cards[0]=%d",cards[0]);
    //字符串
    char dog[3]={'d','o','g'};//不是一个string
    char cat[4]={'c','a','t','\0'};//是一个string
    /*
     字符串常量(使用双引号)不能与字符常量(使用单引号)互换
     字符常量(如's')是字符串编码的简写表示
    */
    
    //读取数据内容
    char mychar[20]={'d','u','g','a','o','d','a'};
    cin.getline(mychar, 6);
    cin.get(mychar, 6);
    
    //4.3  string 类简介  之前自己也经常用
    std::string mystdstring;
    mystdstring="dugaoda  abc";
    //字符串附加
    std::string str1;
    std::string str2;
    std::string str3;
    str1="dugaodaoerjhh";
    str2="gaoda";
    str3=str1+str2;//str3的值为dugaoda,字符串拼接
    
    
    //4.3.2  string类的其他操作
    str1.size();
    str1.length();
    CCLOG("str1.size()=%d",str1.size());
    CCLOG("str1.length()=%d",str1.length());
    str1.empty();//判断是否为空
    str1.insert(2, "d");//再2的位置插入d
    str1.find(d);//查找,搜索返回下标值
    reverse(str1.begin(), str1.end());//字符串反转
    str1.erase(3);//删除第3个之后的所有元素
    str1.erase(str1.begin(),str1.begin()+1);//删除第1到第2个元素
    
    
    
     //字符复制
    char cha1[20];
    char cha2[20]="sdfsdf";
    
    strcpy(cha1, cha2);
    strcat(cha1,cha2);
    
    //4.4  结构体
    struct mystruct
    {
        int number;
        char name[20];
    };
    
    mystruct dugaoda=
    {
        10,
        "dugaoda"
    };
    //上面那种方式可以初始化
    
   /* mystruct dugaoda;
    dugaoda=
    {
        10,
        "dugaoda"
    };
    */
    //上面这种方式初始化就会出现问题,不允许以这种方式写
    
    
    
    //4.4.4  结构数组
    
    mystruct dugaodastruct[2]=
    {
        {10,"dugaoda"},
        {11,"dugaodada"}
    };
    dugaodastruct[0].name;


    //4.5  共用体  用途:当数据项树永两种或更多种格式(但不会同时使用)时,可以节约空间
    union myunion
    {
        int int_abc;
        double double_abc;
    };
    
    myunion du;
    du.int_abc=10;
    du.double_abc=11.2;
    


    
    //4.6 枚举类型
    myenum  dgdenum;
    dgdenum=MYMESSAGE_FIVE;
    CCLog("%d",MYMESSAGE_FIVE);
    
    
    //4.7 指针和自由存储空间
    int updates = 6;
    int * p_updates;
    p_updates=&updates;
    
    *p_updates;//值


    
    //4.7.4  使用new来分配
    int* pn = new int;
    delete pn;
    
    
    //使用new来创建动态数组
    
    int* pna = new int[500];
    pna[0]=0;
    pna[1]=1;
    pna[2]=2;
    
    delete [] pna;
    
    
    
//5.循环和关系表达式
    
    //前zhui格式和后缀格式
    int x;
    x=10;
    x++;
    ++x;
    //组合操作符
    int y;
    y=11;
    x+=y;
    x-=y;
    x*=y;
    x/=y;
    x%=y;
    
    //循环  自己在程序中很少用while 和 do while
    
    
    //while循环
//    while (1) {
//        int ads;
//    }
    
    //do while循环
    int cishu;
    cishu=1;
    do
    {
    cishu+=1;
    }while (cishu<=100);
    
    //操作符?:
    int fuhaoa;
    int fuhaob;
    int fuhaoc;
    fuhaoa=10;
    fuhaob=11;
    fuhaoc=fuhaoa>fuhaob?fuhaoa:fuhaob;
     CCLog("fuhaoc=%d",fuhaoc);
    
    
    //6.5  switch语句
    switch (fuhaoc) {
        case 1:  CCLog("1");
            break;
        case 2:  CCLog("2");
            break;
        case 11: CCLog("2");
            break;
        default:
            break;
    }
    
    //C++输入
    double doublecin;
    cin>>doublecin;
    
    // break 与continue的使用
    //continue之后语句全都跳过,直接跳到for语句执行a++,开始下一个循环。
    //break直接跳出循环
    
    
    // I/O是input/output的缩写,即输入输出端口。每个设备都会有一个专用的I/O地址,用来处理自己的输入输出信息。
    


//#include <fstream>
//    ofstream         //文件写操作 内存写入存储设备
//    ifstream         //文件读操作,存储设备读区到内存中
//    fstream          //读写操作,对打开的文件可进行读写操作
    
    //STL = Standard Template Library,标准模板库,惠普实验室开发的一系列软件的统称
    
    //一般在定义类的时候把数据成员放在私有部分,把成员函数放在公有部分
    
//    
    int side=3;
    int &rd=side;
    
    CCLog("rd=%d",rd);
    
    mhy(10);
    myzhizhen();
    mhy(10);
    
    
    //运算符重载
    HelloWorld temp1;
    HelloWorld temp2;
    temp2.duone=10;
    temp2.dutwo=10;
    temp2.duthree=10;
    temp1+=temp2;
    
    CCLog("temp1.duone=%d",temp1.duone);
//    temp1.duone;
//    temp1.dutwo;
//    temp1.duthree;
    
    //友元函数
    HelloWorld abdddd;
    f_f(abdddd);
    
    //std::map用法,跟vector类似 相当于vector的升级版本
    typedef std::map<int, std::string> ss;
  ss sdf;
    sdf[1]="sd";//插入数据
    sdf[3]="dww";
    sdf[2]="dfs";
    sdf.insert(map<int, std::string>::value_type(10,"10"));//插入数据


    std::map<std::string, std::string> newmap;
    newmap["sdfge"]="sd";
    newmap.size();
    CCLog("%d",newmap.size());


    std::map<std::string, std::string>::iterator newmaptest;
    newmaptest=newmap.begin();
    (*newmaptest);
    for(newmaptest=newmap.begin(); newmaptest != newmap.end(); newmaptest++)
        
    {
        CCLog("%s",newmaptest->first.c_str());
        CCLog("%s",newmaptest->second.c_str());
    }
    
//    sdf.insert(map::value_type(15,"23"));
    std::string i=sdf[3];//只能根据前面的查找后面的值,这边是通过int来查找string的值.i=dfs
    
    
    
    
    
   
    std::map<int, std::string> s2;
    s2[1]="sdf";
    
    
    
//    mymap[1]=1;
    
    //抽象类,有纯虚函数的类就是抽象类,抽象类不能实例化
    smallstudent mystudent;
    
    //构造函数 ,继承,数据的访问权限
    child  mychild;
    child  mychild1;
    mychild.cao=10;
    mychild.mychild(10);
    
    //valarray类
    valarray<int> sd1;//定义一个数组大小为0的int类型的数组
    valarray<double> sd12(8);
    
    
    c sdfsdfsdf;
    
    //类模版的使用
     myCompare<int> cmp1(3,7);  //定义对象cmp1,用于两个整数的比较
    CCLOG("cmp1.max()=%d",cmp1.max());
    CCLOG("cmp1.min()=%d",cmp1.min());
    
    //模版多个参数的使用
    Pals<double, int, 6> msdsfew;
    
    
    //15  嵌套类
    
    
    
    //RTTI 是运行阶段类型识别
    //派生类的地址赋值给基类指针是安全的  相反就不安全了
    //static_cast最接近于C风格转换,但在无关类指针转换时,编译器会报错,提升了安全性;
    //dynamic_cast要求转换类型必须是指针或引用,且在下行转换时要求基类是多态的,如果发现下行转换不安全,dynamic_cast返回一个null指针,dynamic_cast总是认为void*之间的转换是安全的;
    //reinterpret_cast,重解释转换,可以对无关类指针进行转换,甚至可以直接将整型值转成指针,这种转换是底层的,有较强的平台依赖性,可移植性差;两个没有任何关系的类指针之间转换都可以用这个转换实现
    //const_cast可以将常量转成非常量,但不会破坏原常量的const属性,只是返回一个去掉const的变量。
    
    
    //const_cast测试
    const char *c="sdfds";
    char* sdew=const_cast<char*>(c);
    
    //dynamic_cast测试
     CBase b; CBase* pb;
     CDerived dd; CDerived* pdd;
    
     pb = dynamic_cast<CBase*>(&dd);     // ok: derived-to-base
//     pdd = dynamic_cast<CDerived*>(&b);  // 错误的: base-to-derived;如果再基类中声明一个虚函数这样是允许的,但是转换后是空指针
    
    
    //向下转换:  派生类转向基类
    //向上转换:  基类转向派生类
    
    //reinterpret_cast  测试
    AA * adsfx = new AA;
    BB * byikou= reinterpret_cast<BB*>(adsfx);//correct!
    //static_cast  测试
    AA * sdfeq;
    //BB * byikouddd= static_cast<BB*>(sdfeq);
    //static_cast最接近于C风格转换了,但在无关类的类指针之间转换上,有安全性的提升。


    
    //char字符信息,单个字符用char用单引号
    char dfget[20]="dsfgterw";
    char sde='2';
    
    //STL提供一个一组表示容器 迭代起  函数对面和算法的模版
    //vector容器
    vector<int> sdes(3);//定义一个大小为3的容器
    sdes.push_back(3);
    
    
    //vector迭代器
    vector<int>::iterator  abc;
    for ( abc=sdes.begin(); abc!=sdes.end(); abc++)
    {
        CCLOG("%d",*abc);
    }


    //容器种类  stl种有11种容器deque list stack  map vector......
    //list 双向链表
    //deque  双端队列
    //queue  适配器类
    //联合容器 set multiset map multimap
    
    
   
    
//    ofstream         //文件写操作 内存写入存储设备
//    ifstream         //文件读操作,存储设备读区到内存中
//    fstream          //读写操作,对打开的文件可进行读写操作
    
    
    //写
//    ofstream out("test3.txt",ios::out);
//    if (out.is_open()) {
//        out << "This is a line.\n";
//        out << "This is another line.\n";
//        out.close();
//    }


    
    
    
    //读
//    char buffer[256];
//    ifstream in("test3.txt");
//    if (! in.is_open())
//    {
//        cout << "Error opening file"; exit (1);
//    }
//    while (!in.eof() )
//    {
//        in.getline (buffer,100);
//        cout << buffer << endl;
//      }
    
    
    
//读取2进制文件大小
//        const char * filename = "test3.txt";
//    
//        long l,m;
//        ifstream in(filename, ios::in|ios::binary);
//    
//        l = in.tellg();
//        in.seekg (0, ios::end);
//        m = in.tellg();
//        in.close();
//        cout << "size of " << filename;
//        cout << " is " << (m-l) << " bytes.\n";


    
    //多继承  派生类的参数个数必须包含完成所有基类初始化所需的参数个数。
     ABC aa(1, 2, 3, 4);
    
    aa.print();//调用的是ABC类中的print()函数
    aa.B1::print();//调用的是B1类中的print()函数  跟二义性有关系
    aa.B2::print();//调用的是B2类中的print()函数
    
    //aa.b1;错误的写法  pubulic继承只继承基类的public部分,
    
    
    
    
    //递归
    digui(12);
    
    
//    公有继承
    obpub duu;
    duu.ob::vpuba1();//访问基类的vpuba1()函数
    duu.ob::inpuba1;//访问基类的inpuba1


//    私有继承
    obpri gaoo;
    
//    保护继承
   obpro daa;
    
    //宏定义CC_SYNTHESIZE    CC_SYNTHESIZE_PASS_BY_REF 用法
    set_d(10);
    set_nID(12);
    int bddd;
    bddd=get_nID();
    bddd=get_d();


    
    
    int asdse;
    asdse=10;
    
    




    
    
    return true;
}
std::vector<int>& HelloWorld::mydudada()
{
    std::vector<int> iou;
    return iou;
}
//使用const  传递引用
const int& HelloWorld::consttest(const int& b) const
{
    int dsdsd;
    dsdsd=b;
    return dsdsd;
}
c::c()
{
    CCLog("this c ");
}


father::father()
{
    CCLog("father");
    fatherprotec=10;
}
child::child()
{
    CCLog("child");
}
void child::mychild(int a)
{
    e=a;
    CCLOG("e=%d",e);
    CCLOG("fatherprotec=%d",fatherprotec);
//    CCLOG("fatherprotec=%d",b);  //b是私有成员继承的类不能访问
}


void f_f(HelloWorld& tes)
{


//    tes.duone;
    
}
void HelloWorld::digui(int a)
{
     CCLOG(" aaaa= %d",a);
    if (a>10) {
        
        digui(a-1);
    }
    else
    {
        CCLOG("digui a= %d",a);
    }
   
}
void HelloWorld::mhy(int a)
{
    CCLog("a====%d",a);
}
void HelloWorld::test1(int &ab)
{
    CCLog("ab====%d",ab);
}
void*  HelloWorld::myzhizhen()
{
    int* p;
    int a;
    a=3;
    p=&a;
    return  p;
}
HelloWorld& HelloWorld::operator+=(const HelloWorld& test)
{
    
    duone+=test.duone;
    dutwo+=test.dutwo;
    duthree+=test.duthree;


    
    return *this;
}


void HelloWorld::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();


#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值