使用构造函数初始化字符串指针

using a constructor to initialise a string pointer

本文关键字:字符串 指针 初始化 构造函数      更新时间:2023-10-16

我的代码有问题。我有点不知所措。我有一个数据成员,它是指向字符串类型的指针。我使用构造函数作为该指针的取消初始化首字母,然后当我调用主函数中的对象时,初始化的指针指向存储字符串的内存地址并打印内容。这是应该发生的事情,但我无法让程序运行。谁能告诉我哪里出了问题吗?

#include<iostream>
#include<string>
using namespace std;
class NoName{
public:
    NoName(string &sName("Alice In Wonderland") ){};
private:
    string *pstring;
};
int main(){
    //the constructor will be automatically called here once a object is created
    // and the string "Alice in Wonderland" will appear on the screen
    return 0;
}

只需使用std::string成员,并在成员初始值设定项列表中初始化即可

 private:
    string mstring;
 public:
    NoName():mstring("Alice In Wonderland"){} 

您也可以让构造函数接受一个参数,而不是硬编码字符串,并让用户在运行时传递字符串:

NoName(std::string str):mstring(str){}

您不需要指针。通过使用指向std::string的指针,可以抵消std::string提供的隐式手动内存管理的优势。

如果出于某种原因确实需要存储指针,那么需要记住以下几点:

  • 指针的初始化方式类似于new Class
  • 首选初始化成员初始值设定项列表中的类成员
  • 每当你写单词new的时候,想想你要在哪里写delete。(在这种情况下,它进入析构函数
  • 第三条规则:如果你需要一个析构函数(因为delete,你确实需要),那么你也需要一个复制构造函数和复制赋值运算符

这是代码的一种外观:http://ideone.com/21yGgC

#include<iostream>
#include<string>
using std::cout; using std::endl;
using std::string;
class NoName
{
public:
    NoName(string sName = "Alice In Wonderland") :
        pstring(new string(sName))
    {
      cout << "ctor - " << *pstring << endl;
    }
    NoName(const NoName& rhs) :
        pstring(new string(*rhs.pstring))
    {
      cout << "Copy ctor - " << *pstring << endl;
    }
    NoName& operator=(const NoName& rhs)
    {
      *pstring = *rhs.pstring;
      cout << "Copy assignment operator - " << *pstring << endl;
      return *this;
    }
    ~NoName()
    {
        cout << "dtor, my name was " << *pstring << endl;
        delete pstring;
    }
private:
    string *pstring;
};

int main()
{
    NoName m, n("Another name");
    NoName o(m);
    o = n;
    return 0;
}

请注意,如果你不使用不必要的指针,它会变得容易得多:

class Better
{
public:
    Better(string sName = "Alice In Wonderland") :
        m_string(sName)
    {
    }
private:
    string m_string;
};

因为您不需要自定义析构函数,所以也不需要复制构造函数或复制赋值运算符。轻松多了!

您没有正确使用构造函数。首先,创建这个引用参数,并尝试将其初始化为字符串对象(这会带来问题)。其次,你的构造函数从来没有真正做过任何事情。

你需要在指针上调用new,取消引用它,给指向的数据一个值,用std::cout输出取消引用的值,然后在析构函数中用delete清理内存(或者在这种情况下,如果你不打算再次使用该字符串,你可以在使用cout后进行。但如果你仍然需要,可以在析构构函数中进行)。

假设你这样做是为了上课,你的课本应该告诉你如何做这些事情。

EDIT:这也不是默认的构造函数。我把你的标签改得很合适。