0

コードに問題があります。私は少し困惑しています。文字列型へのポインターであるデータ メンバーがあります。このポインターへのデフォルトのイニシャラーとしてコンストラクターを使用し、メイン関数でオブジェクトを呼び出すと、初期化されたポインターは、文字列が格納されているメモリアドレスを指し、内容を出力します。それが起こるはずですが、プログラムを動作させることができません。誰かが私がどこで間違っているのか教えてください。

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

3 に答える 3

5

std::stringメンバーを使用して、メンバー初期化子リストで初期化するだけです。

 private:
    string mstring;

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

また、文字列をハードコーディングする代わりにコンストラクターにパラメーターを取り込ませ、ユーザーが実行時に文字列を渡せるようにすることもできます。

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

ポインタは必要ありません。へのポインタを使用すると、std::stringによって提供される暗黙的な手動メモリ管理の利点が無効になりますstd::string

于 2013-02-08T16:11:02.403 に答える
2

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!

于 2013-02-08T17:02:18.603 に答える