免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3061 | 回复: 8
打印 上一主题 下一主题

private 拷贝构造函数 c++ [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-09-02 15:28 |只看该作者 |倒序浏览
各位大侠,小弟今天遇到个问题:

我打算看看private拷贝构造函数能不能在类定义内部使用的问题,或者是去证实它。
有一个叫做show_val_ref的函数,采用值传递的方式,我的本意是希望调用private拷贝构造,可惜结果不是想要的,并没有执行拷贝构造!
代码如下:
#include <iostream>
using namespace std;
class cntor
{
  public:
explicit  cntor(int a){cout<<"in the defaut constructor!"<<endl; m_a = a;}
  void show_val() const;
  void test();

  private:
  cntor(const cntor& cr);
  cntor& operator =(const cntor& cr){cout<<"assgin!"<<endl;return *this;}
  void show_val_ref(cntor cr);
  int m_a;//data member!
};

cntor::cntor(const cntor& cr)
{
cout<<"in the copy constructor!"<<endl;
m_a = cr.m_a;
m_a++;
}
void cntor::show_val() const
{
  cout<<"the value is :" <<m_a <<endl;
}
                         void cntor::show_val_ref( cntor cr)
                         {
                           cr.show_val();//not (*this)
                         }
void cntor::test()
{
  cntor cr_one(100);
  show_val_ref(cr_one);
}
                               int main()
                            {
                               cntor obj(5);
                                obj.test();
                                return 0;
                              }
AIX平台下的运行结果为:
in the defaut constructor!
in the defaut constructor!
the value is :100

论坛徽章:
0
2 [报告]
发表于 2011-09-02 15:38 |只看该作者
有人能给个说法么,期待大牛出现
另外,如果把拷贝构造也声明为explicit的,则编译不通过,说是类型从cntor到cntor转换失败

论坛徽章:
0
3 [报告]
发表于 2011-09-02 15:38 |只看该作者
有人能给个说法么,期待大牛出现
另外,如果把拷贝构造也声明为explicit的,则编译不通过,说是类型从cntor到cntor转换失败

论坛徽章:
0
4 [报告]
发表于 2011-09-02 15:39 |只看该作者
你test函数中并未调用拷贝函数吧。
改成这样试一试
void cntor::test()
{
  cntor t(100);
  cntor cr_one(&t);
  cntor cr_one1 = t;
  show_val_ref(cr_one);
}

论坛徽章:
0
5 [报告]
发表于 2011-09-02 15:44 |只看该作者
不过你上面的程序win32平台,gcc编译后的运行结果为:
in the defaut constructor!
in the defaut constructor!
in the copy constructor!
the value is :101

如何解释?

论坛徽章:
0
6 [报告]
发表于 2011-09-02 15:45 |只看该作者
回复 4# syoubin_sai


    我当时是认为,值传递的时候会发送 临时对象的拷贝构造,现在看来也许不会!至少对于这里的private拷贝构造是如此。
  不过还是谢谢您的解答。

论坛徽章:
0
7 [报告]
发表于 2011-09-02 15:47 |只看该作者
回复 5# syoubin_sai


    看来我的猜想在win32平台是正确的,哈哈。值传递时发生了拷贝构造!!

论坛徽章:
0
8 [报告]
发表于 2011-09-02 15:49 |只看该作者
刚开始学c++领悟不太透彻。
请问
void cntor::test()
{
  cntor cr_one(100);
  show_val_ref(cr_one);
}
中为什么调用了private的拷贝函数呢?

论坛徽章:
0
9 [报告]
发表于 2011-09-02 15:53 |只看该作者
值传递时发生了拷贝构造!!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP