1. 程式人生 > >C++重載的構造函數不能互相調用

C++重載的構造函數不能互相調用

構造函數 this public clu span out sta ++ tor

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++重載的構造函數不能互相調用