c++ sample

本文介绍了C++编程中的位移操作,如何通过位移来组合和拆分整数。此外,还讨论了紧凑结构在结构体中的应用,以及友元类的概念和使用示例。同时,涵盖了函数指针、指针交换和计算,成员函数指针的使用,以及模板在C++中的多种用法,包括函数模板、特例化和嵌套模块特例化等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++ sample

位移凑数
stt st1 = {i1=222, i2=333};
int t1 = (st1.i1 << 16 | st1.i2);    //i1,i2合体, i1左移到高位, i2放到右边低位
int i1 = (t1 >> 16);    //右移去低位, 剩i1
int i2 = (t1 ^ (i1 << 16);    //去左边高位头, 剩i2


紧凑结构
struct S1 {
    int32_t a;
    int b;
    int c;
} __attribute__ ((packed));


友元类
class B {
    public :
    int geta();
};

class A {
    private :
    int a;
    friend class B;
};

int B::geta() {
    A a1;
    a1.a = 2;
    return a1.a;
}

B b;
b.geta() == 2;

函数指针
int func(int x); /* 声明一个函数 */
int (*f) (int x); /* 声明一个函数指针 */
f=func; /* 将func函数的首地址赋给指针f */
f = &func;

int add(int a, int b);
int subtraction(int a, int b);

struct p_fun {
    int (*pFunAdd) (int a, int b);
    int (*pFunSubtraction) (int a, int b);
};

int main() {
    p_fun pFun;
    pFun.pFunAdd = add;
    pFun.pFunSubtraction = subtraction;
    printf("%d, %d", pFun.pFunAdd(1, 2), pFun.pFunSubtraction(2, 1));
    return 0;
}

指针交换
{
    int i;
    i = *p1;    //p1缓存到i
    *p1 = *p2;
    *p2 = i;    //p2=原p1
}
指针计算
{
    *p, *q;
    q = p - 1;
    p - q == 1;                //偏移
    (int)p - (int)q = 8;    //地址值
}

成员函数指针
class MyClass {
public:
    static int FunA(int a, int b) {return a + b;}
 
    void FunB() {...}
 
    void FunC() {}
 
    int pFun1(int (*p)(int, int), int a, int b) {return (*p)(a, b);}
 
    void pFun2(void (MyClass::*nonstatic)()) {(this->*nonstatic)();}
};
 
int main() {
    MyClass* obj = new MyClass;
    // 静态函数指针的使用
    int (*pFunA)(int, int) = &MyClass::FunA;
    cout << pFunA(1, 2) << endl;
     
    // 成员函数指针的使用
    void (MyClass::*pFunB)() = &MyClass::FunB;
    (obj->*pFunB)();
     
    // 通过 pFun1 只能调用静态方法
    obj->pFun1(&MyClass::FunA, 1, 2);
     
    // 通过 pFun2 就是调用成员方法
    obj->pFun2(&MyClass::FunB);
    obj->pFun2(&MyClass::FunC);
 
    delete obj;
    return 0;
}

functionoid样例:
// 成员指针函数基类
class Funct {
 public:
   virtual int doit(int x) = 0;
   virtual ~Funct() = 0;
};
inline Funct::~Funct() {}

typedef Funct* FunctPtr;

// 成员指针函数实例1
class Funct1 : public Funct {
 public:
    Funct1(int y) : _y(y) {}
    virtual int doit(int x) {return x * _y;}
private:
    int _y;
};

int main() {
    // functionoid成员函数指针数组
    FunctPtr array[1];

    // functionoid模式初始化
    array[0] = new Funct1(222);
        // 可以通过不同的ctor参数, 建立同构异参函数环境
        //array[x] = new Funct1(333);
        // 可以对同基不同继承类合并管理
        //array[y] = new Funct2(333, 666);
        //上述2者结合, 可模拟不定个数参数调用

    // functionoid模式调用
    cout << array[0]->doit(333) << endl;
    delete array[0];
    return 0;
}


强行指定模板类型
template<typename T> void f(){...}        // T not show use
f<int>();          // type T will be int in this call
f<std::string>();  // type T will be std::string in this call
例如:f<long>(42);    // param is int, but to be long    

模板特例化
template<typename T> void foo(const T& x){...  ← implementation details when T is neither int nor std::string }
上面模板有2个类型需override
template<> void foo<int>(const int& x) { ...  ← implementation details when T is int }
template<> void foo<std::string>(const std::string& x) { ...  ← implementation details when T is std::string }

嵌套模块特例化
template<typename T> inline void foo_part(const T& x) {... small amount of code used when T is neither int nor std::string ...}
template<> inline void foo_part<int>(const int& x) {... small amount of code used only when T is int ...}
template<> inline void fooo_part<std::string>(const std::string& x) {... small amount of code used only when T is std::string ...}
使用, 嵌套内实现同逻辑, 节省重复代码
template<typename T> void foo(const T& x) {foo_part(x);}

模板不是一个类或函数。 模板是一个“模式”,编译器用来生成的相似的类或者函数。
为了让编译器生成的代码,它必须同时看到模板的定义和特定类型
    例如,如果你想使用一个foo<int>,编译器必须同时看到foo模板和你要调用具体的foo<int>
异常调用实例:
b.cpp : {Foo<int> f; f.someMethod(5);},编译器将看到Foo<int>,但不会同时看到模板代码,
    因此编译器不会产生foo <int>::someMethod()的代码,因此会产生函数链接错误
解决:
1 模板函数在定义时实现
2 实现特例化+函数调用强行指定模板类型,
    foo_impl.cpp :
        #include "foo.cpp"
        template void foo<int>();
    b.cpp : {foo<int>();}

模板派生类不能直接使用一个继承自模板基类的嵌套类型/成员变量
template<typename T> class B {class Xyz {...}; typedef int Pqr; void f() {}}
template<typename T> class D : public B<T>
    Xyz x; / B<T>::Xyz x; 报错
    typename B<T>::Xyz x; ok
    f(); 报错
    两边改为 this->f(); ok
或者给Xyz/f()指定名空间D<T>::,否则可能被解释为全局变量

指定了“匹配”功能, std::vector<Fred*>中找到一个匹配Fred的元素
template<typename T> class DereferencedEqual {
public:
    DereferencedEqual(const T* p) : p_(p) { }
    bool operator() (const T* p2) const { return *p_ == *p2; }
private:
    const T* p_;
};
void matchFred(std::vector<Fred*> v, const Fred& match){
    std::find_if(v.begin(), v.end(), DereferencedEqual<Fred>(&match));
    ...
}


#include <iostream>
#include <map>
#include <vector>
using namespace std;

template<typename K,typename V>
class ccmap {
public:
    ccmap() {}
    ~ccmap() {_map.clear();}
    V operator[](const K k) {
        auto it = _map.find(k);
        if (it == _map.end()) {
            throw "fuck";
        }
        return it->second;
    }
    typename std::map<K,V>::iterator find(const K k) {return _map.find(k);}
    
    typename std::map<K,V>::iterator end() {return _map.end();}
    typename std::map<K,V>::const_iterator end() const {return _map.end();}
    
    typename std::map<K,V>::iterator begin() {return _map.begin();}
    typename std::map<K,V>::const_iterator begin() const {return _map.begin();}
    
    typename std::map<K,V>::iterator rend() {return _map.rend();}
    typename std::map<K,V>::iterator rbegin() {return _map.rbegin();}
    
    void insert(const K k) {_map[k] = V();}
    void insert(const K k, const V v) {_map[k]=v;}
    void insert(const std::pair<K, V>& p) {_map[p.first] = p.second;}
private:
    std::map<K, V> _map;
};

void F1(int a, int b){}
void F2(const ccmap<uint32_t, uint32_t>& mapf) {
    for (auto it : mapf) {
        cout << "for mapff: " << it.first << "," << it.second << endl;
    }
}

int main()
{
    //ccmap<uint32_t, uint32_t> mapf;
    //mapf[1] = F1;
    //mapf.insert(1, 23);
    //mapf.insert({2, 66});
    //char name[100];
    //cout << "lenn: " << (name[0]=='\0') << endl;
    //cout << "mapf: " << (mapf.find(1)->second) << endl;
    //cout << "mapf: " << mapf[1] << endl;
    //cout << "mapf: " << mapf[2] << endl;
    //F2(mapf);
    ccmap<uint32_t, ccmap<uint32_t, std::vector<uint32_t>>> mapffv;
    mapffv.insert({1, ccmap<uint32_t, std::vector<uint32_t>>()});
    mapffv.find(1)->second.insert({1, std::vector<uint32_t>()});
    mapffv.find(1)->second.find(1)->second.push_back(222);
    for (auto it2 = mapffv.find(1)->second.find(1)->second.begin(); it2 != mapffv.find(1)->second.find(1)->second.end(); ++it2) {
        cout << "mapffv: " << *it2 << endl;
    }
    uint64_t id = (uint64_t)10 << 32 | (uint64_t)456 << 16 | (uint64_t)235;
    uint16_t m1 = (uint64_t)id >> 32;
    uint16_t m2 = (id ^ ((uint64_t)m1<<32))>>16;
    uint16_t m3 = (id ^ ((uint64_t)m1<<32))^(m2<<16);
    cout << "i: " << m1 << ' '<< m2 << ' ' << m3 << endl;
    return 0;
}


#include <iostream>
#include <map>
#include <vector>
#include <set>
using namespace std;

class Obj {
public:
    Obj(int i) {id=i;op=0;v1=0;v2=0;}
    void Print() {
        cout << id << endl;
    }
    void set_op(int i) {op=i;}
    void set_v1(int i) {v1=i;}
    void set_v2(int i) {v2=i;}
    int get_op() {return op;}
    int get_v1() {return v1;}
    int get_v2() {return v2;}
private:
    int id;
    int op;
    int v1;
    int v2;
};
class Cmp {
public:
    bool operator() (Obj* lv, Obj* rv) const {
        /*if (lv->get_op() == rv->get_op()) {
            if (lv->get_v1() == lv->get_v1()) {
                return lv->get_v2() > rv->get_v2();
            }
            return lv->get_v1() > rv->get_v1();
        }
        return lv->get_op() < rv->get_op();
        */
        return false;
    }
};
typedef std::multiset<Obj*, Cmp> Rk;
typedef std::map<int, Rk> Ok;
void update(Ok& okr, int k, Obj* pO, int opt=0) {
    if (1 == opt) {
        auto ret = okr[k].equal_range(pO);
        for (auto it = ret.first; it != ret.second;) {
            if (*it == pO) {
                okr[k].erase(it++);
                cout << "erase " << pO << endl;
            } else {
                ++it;
            }
        }
    } else {
        okr[k].insert(pO);
    }
}
void Print(Ok& okr, int ord) {
    cout << "--" << ord << "--" << endl;
    for (auto it = okr[1].begin(); it != okr[1].end(); ++it) {
        (*it)->Print();
    }
}
int main()
{
    Ok okr;
    Obj o1(1);
    o1.set_op(1);o1.set_v1(33);o1.set_v1(21);
    update(okr, 1, &o1);
    Obj o2(2);
    o2.set_op(10);o2.set_v1(13);o2.set_v1(16);
    update(okr, 1, &o2);
    Obj o3(3);
    o3.set_op(1);o3.set_v1(9);o3.set_v1(6);
    update(okr, 1, &o3);
    //Obj o4(4);
    //o4.set_op(1);o4.set_v1(33);o4.set_v1(21);
    //update(okr, 1, &o4);
    Print(okr, 1);
    
    update(okr, 1, &o1, 1);
    o1.set_op(8);
    update(okr, 1, &o1);
    Print(okr, 2);
    cout << "ok" << (uint32_t)-1 << endl;
    //cout << "i: " << m1 << ' '<< m2 << ' ' << m3 << endl;
    return 0;
}


unicode范围    二进制表示范围
>=252 len=1
U-00000000 - U-0000007F    0xxxxxxx
>=192 len=2
U-00000080 - U-000007FF    110xxxxx 10xxxxxx
>=224 len=3
U-00000800 - U-0000FFFF    1110xxxx 10xxxxxx 10xxxxxx
>=240 len=4
U-00010000 - U-001FFFFF    11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
>=248 len=5
U-00200000 - U-03FFFFFF    111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
>=252 len=6
U-04000000 - U-7FFFFFFF    1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值