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");
    }
  • 相关阅读:
    TensorFlow学习笔记--CIFAR-10 图像识别
    第二章--第二节:注释
    webbrowser
    RichViewEdit
    RichEdit
    TreeView
    RichView
    ListView
    DesktopLoader服务程序
    Delphi实现程序只运行一次并激活已打开的程序
  • 原文地址:https://www.cnblogs.com/jj81/p/10788155.html
Copyright © 2011-2022 走看看