c++ 尽量不要用memset去对类的实例清0

#include "iostream"
#include "memory.h"
using namespace std;

class A
{
  public:
    std::string tostring()
    {
        std::string buf;
        buf.append(std::to_string(major))
            .append(" ")
            .append(std::to_string(cmd));
        return buf;
    }

  protected:
    short major = 7;
    int cmd = 79;
};


template
class B {
public:
    std::string tostring()
    {
        std::string buf;
        for (int i = 0; i < end(mbuf)-begin(mbuf); i++){
            buf.append(std::to_string(mbuf[i])).append(" ");
        }

        buf.append(std::to_string(m_len));
        return buf;
    }
    
    char mbuf[MAX_SIZE];
    int  m_len;
};

class C : public A{
public:
    static const unsigned short MAJOR = 7;
    static const unsigned short MAINOR = 66;
    static const unsigned short CMD = 819;

    std::string tostring()
    {
        std::cout << "A " << A::tostring() << std::endl;
        std::string buf;
        buf.append(std::to_string(MAJOR)).append(" ");
        buf.append(std::to_string(MAINOR)).append(" ");
        buf.append(std::to_string(CMD)).append(" ");
        buf.append(std::to_string(idx)).append(" ");
        buf.append(std::to_string(sec)).append(" ");

        
        std::cout << "B " << cn.tostring() << std::endl;
        std::cout << "C " << buf << std::endl;

        return buf;
    }

    int  idx = 92;
    int  sec = 82;
    B<7,short> cn; 
};

int main(){
    C c;
    memset(&c,0,sizeof(c));
    c.tostring();

    return 0;
}
$ ./a.exe
A 0 0
B 0 0 0 0 0 0 0 0
C 7 66 819 0 0

 

你可能感兴趣的:(c++)