#include <iostream>
#include <string>
#include <vector>
using namespace std;
class HasPtr{
public:
//constructor accepts a string
HasPtr(const string &s = string()) : ps(new string(s)), i(0), use(new size_t(1)) {}
//copy constructor
HasPtr(const HasPtr &h) : ps(h.ps), i(h.i), use(h.use) { ++*use; }
//copy assignment operator
HasPtr &operator=(const HasPtr &h)
{
++*h.use;
if(--*use == 0)
{
delete ps;
delete use;
}
ps = h.ps;
i = h.i;
use = h.use;
return *this;
}
~HasPtr()
{
if(--*use == 0)
{
delete ps;
delete use;
}
}
//private:
string *ps;
int i;
size_t *use;
};
int main()
{
HasPtr h("hi mom");
HasPtr h2 = h;
HasPtr h3("hi dad");
h2 = h3;
cout << "h: " << *h.ps << endl;
cout << "h2: " << *h2.ps << endl;
cout << "h3: " << *h3.ps << endl;
}
输出为:
h: hi mom
h2: hi dad
h3: hi dad
我认为输出应为:
h: hi dad
h2: hi dad
h3: hi dad
我认为输出应该如上所述:
h是&#34;嗨妈妈&#34;,h2分享h1,所以h2是&#34;嗨妈妈&#34;,h3是&#34;嗨爸爸&#34;,我认为{{1因为h2共享h1而改变了h1,但它没有。
我做错了什么?
答案 0 :(得分:3)
以下是什么:
HasPtr h("hi mom");
HasPtr h2 = h;
h.ps ---> "hi mom" <--- h2.ps
然后在下一个语句中,您更改h2
,但这不会影响h
:
HasPtr h3("hi dad");
h2 = h3;
h2.ps ----> "hi dad" <--- h3.ps
|
XXX changed
|
"hi mom" <--- h.ps
指针是指向同一地址的不同实例。示例:
int a = 5, c = 1;
int *p1 = &a, *p2 = &a;
更改p1
(即p1 = &c
)不会影响p2
。
答案 1 :(得分:2)
我们会更清楚地考虑一个简化的例子
int x = 10;
int y = 20;
int *h = &x;
int *h2 = h;
现在h
和h2
指向x
。您可以检查此输出指针指向的对象。例如
std::cout << "*h = " << *h << ", *h2 = " << *h2 << std::endl;
然后你正在使用第三个指针
int *h3 = &y;
h2 = h3;
现在h2
和h3
指向y
。 h
未被更改。你也可以看看这个
std::cout << "*h2 = " << *h2 << ", *h3 = " << *h3 << std::endl;
std::cout << "*h = " << *h << std::endl;
语句
中的对象也是如此HasPtr h("hi mom");
HasPtr h2 = h;
HasPtr h3("hi dad");
h2 = h3;
只有相应的指针(ps)包含在类的对象中。
这是一个演示解释的程序
#include <iostream>
#include <string>
int main()
{
std::string hi_mom( "hi mom" );
std::string hi_dad( "hi dad" );
std::string *h = &hi_mom;
std::string *h2 = h;
std::cout << "*h = " << *h << ", *h2 = " << *h2 << std::endl;
std::string *h3 = &hi_dad;
h2 = h3;
std::cout << "*h2 = " << *h2 << ", *h3 = " << *h3 << std::endl;
std::cout << "*h = " << *h << std::endl;
}
它的输出是
*h = hi mom, *h2 = hi mom
*h2 = hi dad, *h3 = hi dad
*h = hi mom