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成员并在Member initializer list中对其进行初始化:

 private:
    string mstring;

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

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

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

您不需要指针。通过使用指向std::stringYou 的指针抵消了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 回答
0

您没有正确使用构造函数。首先,您创建此引用参数并尝试将其初始化为一个字符串对象(这是在寻找问题)。其次,您的构造函数实际上从不做任何事情。

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

假设您正在为一堂课这样​​做,您的教科书应该告诉您如何做这些事情。

编辑:这也不是默认构造函数。我更改了您的标签以适当匹配。

于 2013-02-08T17:53:59.873 回答