使用构造函数初始化字符串指针
using a constructor to initialise a string pointer
我的代码有问题。我有点不知所措。我有一个数据成员,它是指向字符串类型的指针。我使用构造函数作为该指针的取消初始化首字母,然后当我调用主函数中的对象时,初始化的指针指向存储字符串的内存地址并打印内容。这是应该发生的事情,但我无法让程序运行。谁能告诉我哪里出了问题吗?
#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:这也不是默认的构造函数。我把你的标签改得很合适。
相关文章:
- strcpy 在类中无法使用字符串指针
- 如何将字符串指针数组转换为字符串类型的智能指针向量?
- 使用conststd::字符串指针作为函数参数
- 将字符串指针传递到C++和Xcode 11.1中不同线程上运行的函数
- OOP 和字符串指针的奇怪行为
- 在 C++ 中通过字符串指针复制字符串变量中的字符串
- 删除字符串指针在struct中的内存
- 字符串指针的排序向量
- C#C /CLR处理REF参数和字符串指针
- 问题在字符串指针中存储单词
- 如何在C++中从字符串指针中获取字符
- 如何使用字符串指针访问映射的键
- 将字符串指针与 NULL 以及 NULL 字符进行比较的目的
- 如何获取字符串指针的值?
- C++ 字符串* 指针未在控制台中正确打印
- Visual Studio C++ 空字符串指针
- 管理C#中返回的字符串指针
- 指向C++中的字符串指针数组的指针
- 如何将结果集设置为字符串指针
- 如何初始化字符串指针