码迷,mamicode.com
首页 > 编程语言 > 详细

C++重载的构造函数不能互相调用

时间:2018-02-23 23:41:14      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:互相调用   argv   ring   stc   方法   value   clu   调用   delete   

java类里的重载构造函数可以互相调用,如下代码:

 1 public class TestConstructor {
 2     private int value;
 3 
 4     public TestConstructor(int value) {
 5         this.value = value;
 6         System.out.println("constructor1:"+this);
 7     }
 8 
 9     public TestConstructor() {
10         this(10);
11         System.out.println("constructor2:"+this);
12     }
13 
14     public static void main(String[] args) {
15         TestConstructor test = new TestConstructor();
16         System.out.println(test.value);
17         System.out.println(test);
18     }
19 }

代码执行结果是:

constructor1:TestConstructor@74a14482
constructor2:TestConstructor@74a14482
10
TestConstructor@74a14482

可见结果是预期的,对value赋值是成功的,且只创建了一个对象。

 

 

来看一下C++实现(头文件省略):

 1 #include "testconstructor.h"
 2 #include <QDebug>
 3 
 4 TestConstructor::TestConstructor()
 5 {
 6 //    this(10);
 7     TestConstructor(10);
 8     qDebug()<<"constructor1:"<<this;
 9 }
10 
11 TestConstructor::TestConstructor(int value)
12 {
13     this->value = value;
14     qDebug()<<"constructor2:"<<this;
15 }
 1 #include "testconstructor.h"
 2 #include <QDebug>
 3 
 4 int main(int argc, char *argv[])
 5 {
 6     TestConstructor *t = new TestConstructor();
 7     qDebug()<<t->value;
 8     qDebug()<<t;
 9     delete t;
10 }

代码执行结果是:

constructor2: 0x22fcf0

constructor1: 0xdadfb0

15574896

0xdadfb0 

一方面,对value设置的值没有生效,另一方面,两个构造函数创建了两个不同的对象,说明C++不能像java那样构造函数之间互相调用。

解决方法:

大多数构造函数互相调用的需求应该是有默认参数,在C++的函数声明中可以直接设置默认传参(java不支持默认参数),这样就不需要构造函数重载了:

TestConstructor(int value = 10);

  

C++重载的构造函数不能互相调用

标签:互相调用   argv   ring   stc   方法   value   clu   调用   delete   

原文地址:https://www.cnblogs.com/AuroraMini/p/8463572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!