简体   繁体   中英

using a constructor to initialise a string pointer

i am having trouble with my code. I am abit stumped. I have a data member which is a pointer to a string type. I use the constructor as a defualt initialer to this pointer, then when I call an object in the main function the intialised pointer to points to the memory address where the string is stored and prints the contents. That is what is supposed to happen, but I can't get the program to work. May somebody please tell me where I am going wrong?

#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;
}

Just simply use a std::string member and initialize it in Member initializer list :

 private:
    string mstring;

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

You could also let the constructor take in a parameter instead of hardcoding the string and let the user pass the string at run-time:

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

You do not need a pointer. By using a pointer to std::string You nullify the advantages of implicit manual memory management offered by std::string .

If you really need to store a pointer for some reason, then there are some points to remember:

  • Pointers are initialized like new Class
  • Prefer to initialize class members in the member initializer list
  • Any time you write the word new think about where you're going to write delete . (In this case it goes in the destructor.
  • Rule of Three: If you need a destructor (you do, because of delete ), then you also need a copy constructor and copy assignment operator.

This is one way your code could look: 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;
}

Notice how much easier it is if you don't use the unnecessary pointer:

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

Because you don't need the custom destructor, you also don't need the copy constructor or copy assigment operator either. Much easier!

You're not using the constructor properly. First of all, you create this reference parameter and try to initialize it to a string object (that's asking for problems). Second, your constructor never actually does anything.

You need to call new on your pointer, dereference it and give the data pointed to a value, output the dereferenced value with std::cout and then clean the memory up with delete in the destructor (or in this case, you can do it after you use cout if you're not planning on using that string again. But do it in the destructor if you need it still).

Assuming you're doing this for a class, your textbook should tell you how to do these things.

EDIT: this is also not the default-constructor. I changed your tag to match appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM