如果你真的需要存储出于某种原因指针,则有几点要记住:
- 指针是像
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;
};
因为你不需要自定义析构函数,你也不需要拷贝构造函数或可以复制分配新建分配FY运营商。更容易!
您发布的代码并没有做你说的那样。另外,你的构造函数声明不会做你认为它做的事情。 – us2012 2013-02-08 16:11:44
所以更努力... – Josh 2013-02-08 16:22:45
我认为你有很多关于构造函数,指针和引用的学习。 – MGZero 2013-02-08 17:50:08