注册 登录
编程论坛 C++教室

含有指针对象的级联赋值为什么会出问题?

wanghui737 发布于 2013-06-27 21:38, 568 次点击
程序代码:
class num
{
  public:
   num()={n=new int;*n=1;cout<<"构造函数执行\n";}

   ~num(){delete n;n=NULL;cout<<析构函数执行\n";}

   int get(){return *n;}

   void set(int x){*n=x;}

   num operator=(const num&r)
     { cout<<“operator=函数在调用\n";
       *n=r.get();
       return *this;
      }


 private:
   int *n;
}


int main()
{
   num   one,two;
   one.set(1);
    num  three;
   three=two=one;
   cout<<two.get();
   return 0;
}
运行结果输出的two.get()的值是个随机数,而不是1,
为什么主函数中 执行  two=one;就可以使two.get()的值为1,而执行three=two=one;就出问题呢?问题出在哪里,请帮详细解释下,小弟是个新手,谢谢了
4 回复
#2
wanghui7372013-06-27 21:48
哪位大哥帮忙指点一下啊。。。
#3
peach54602013-06-28 06:07
不要用连等不就好了...
#4
rjsp2013-06-28 08:39
这么多语法错误呀!既然你都能编译通过的,为什么不将代码拷贝粘贴上来呐?

程序代码:
#include <iostream>

class num
{
public:
    num( int n=0 ) : n_( new int(n) )
    {
        std::cout << "构造\n";
    }
    num( const num& rhs ) : n_( new int(*rhs.n_) )
    {
        std::cout << "拷贝\n";
    }
    num& operator=( const num& rhs )
    {
        std::cout << "赋值\n";
        *n_ = *rhs.n_;
        return *this;
    }
    ~num()
    {
        std::cout << "析构\n";
        delete n_;
    }

    //
   
//int get() const
   
//{
   
//    return *n_;
   
//}
   
//void set( int x )
   
//{
   
//    *n_ = x;
   
//}

private:
    int* n_;

    friend std::ostream& operator<<( std::ostream& os, const num& obj );
};

std::ostream& operator<<( std::ostream& os, const num& obj )
{
    return os << *obj.n_;
}

using namespace std;

int main()
{
    num one(1), two;
    two = one;
    cout << two << endl;

    num three(two);
    cout << three << endl;

    return 0;
}

#5
yuccn2013-06-28 08:42
num operator=(const num&r)
    {
        cout<<"operator=函数在调用\n";
        *n=r.get();
        return *this;
    }
改成
num &operator=(const num&r)
    {
        cout<<"operator=函数在调用\n";
        *n=r.get();
        return *this;
    }

注意前面有个&
1