zoukankan      html  css  js  c++  java
  • C++ | char* 在类中实践笔记

      在C++中,当类中定义有char * 变量时,在传参,构造函数,复制构造函数如何创建及赋值,来一个简单的例子就明了:

    #include<iostream>
    #include<string>
    #pragma warning(disable: 4996)
    using namespace std;
    
    class Goods {
    public:
        Goods();
        Goods(const char* _name, int _id);
        Goods(const Goods& goods);
        void Printf();
        //省略....
    private:
        char *name;
        int id;
    };
    
    Goods::Goods(){}
    Goods::Goods(const char* _name, int _id) :name(new char[strlen(_name) + 1]), id(_id) {
        strcpy(name, _name);
    }
    Goods::Goods(const Goods& goods) : name(new char[strlen(goods.name) + 1]), id(goods.id) {
        strcpy(name,goods.name);
    }
    void Goods::Printf() {
        cout << this->id << "  " << this->name << endl;
    }
    int main() {
        Goods goods("雪碧",1);
        goods.Printf();
        system("pause");
    }
  • 相关阅读:
    spring4-2-bean配置-2-属性注入细节
    内存管理tcmalloc
    并发视频,怎么hold住高并发
    struts总结
    最近想玩的一个方向
    虚拟化技术漫谈
    陈硕的博客
    木铎
    安全编程资源-苹果
    POOL
  • 原文地址:https://www.cnblogs.com/jj81/p/10788155.html
Copyright © 2011-2022 走看看