Jos*_*osh 0 c++ string constructor
我的代码有问题.我很难过.我有一个数据成员,它是一个指向字符串类型的指针.我使用构造函数作为此指针的defualt initialer,然后当我在main函数中调用一个对象时,初始化指针指向存储字符串的内存地址并打印内容.这应该是应该发生的,但我不能让程序工作.请问有人请告诉我哪里出错了?
#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;
}
Run Code Online (Sandbox Code Playgroud)
只需使用一个std::string成员并在Member initializer list中初始化它:
private:
string mstring;
public:
NoName():mstring("Alice In Wonderland"){}
Run Code Online (Sandbox Code Playgroud)
你也可以让构造函数接受一个参数,而不是硬编码字符串,让用户在运行时传递字符串:
NoName(std::string str):mstring(str){}
Run Code Online (Sandbox Code Playgroud)
你不需要指针.通过使用指向std::string您的指针,可以消除由隐式手动内存管理提供的优势std::string.