0%

C++之类和动态内存分配

C++之类和动态内存分配……

动态内存与类

  • stringbad.h

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #ifndef __STRINGBAD_H__
    #define __STRINGBAD_H__

    #include <iostream>

    using namespace std;

    class StringBad
    {
    private:
    char *str;
    int len;
    static int num_strings;//不能对static变量在类定义中直接赋值,否则会报错,const除外
    public:
    StringBad(const char *s);
    StringBad();
    ~StringBad();
    friend ostream &operator<<(ostream &os, const StringBad &st);
    };

    #endif
  • stringbad.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    #include "stringbad.h"
    #include <cstring>

    int StringBad::num_strings = 0;

    StringBad::StringBad(const char *s) // StringBad str("Hello world")
    {
    len = strlen(s);
    str = new char[len + 1];
    strcpy(str, s);
    num_strings++;
    cout << num_strings << ": \"" << str << ". \"" << endl;
    }

    StringBad::StringBad()
    {
    len = 4;
    str = new char[4];
    strcpy(str, "C++");
    num_strings++;
    cout << num_strings << ": \"" << str << ". \"" << endl;
    }

    StringBad::~StringBad()
    {
    cout << "\"" << str << "\" object deleted." << endl;
    --num_strings;
    cout << num_strings << " left." << endl;
    delete []str;
    }

    ostream &operator<<(ostream &os, const StringBad &st)
    {
    os << st.str;
    return os;
    }
  • vegnews.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    #include <iostream>
    #include "stringbad.h"

    void callme1(StringBad &rsb);
    void callme2(StringBad sb);

    int main(void)
    {
    StringBad headline1("Hello world");
    StringBad headline2("Good morning");
    StringBad sports("I love you, Rick");

    cout << "headline1: " << headline1 << endl;
    cout << "headline2: " << headline2 << endl;
    cout << "sports: " << sports << endl;

    callme1(headline1);
    callme2(headline2);

    return 0;
    }

    void callme1(StringBad &rsb)
    {
    cout << "String passed by reference:" << rsb << endl;
    }

    void callme2(StringBad sb)
    {
    cout << "String passed by value: " << sb << endl;
    }
  • 结果如下:

    屏幕截图_20230225_222952

  • 不能对static变量在类定义中直接赋值,否则会报错,static const类型除外。其通常在类的声明cpp文件中赋初始值一次

  • callme2(headline2)中使用直接赋值的方式相当于将StringBad sb=headline2,而这条语句会触发类的自动类型转换,即会调用符合条件的构造函数,但不存在符合条件的构造函数(符合条件的构造函数为StringBad(const StringBad &)

  • 而当使用一个对象来初始化另一个对象时,编译器将自动生成上述构造函数,故实际只存在三个指针,但删除时却需要删除四个指针,故会发生报错


欢迎来到ssy的世界