Overloaded constructors in Java classes can call each other, as in the following code:
1 Public classTestConstructor {2 Private intvalue;3 4 PublicTestConstructor (intvalue) {5 This. Value =value;6System.out.println ("Constructor1:" + This);7 }8 9 PublicTestConstructor () {Ten This(10); OneSystem.out.println ("Constructor2:" + This); A } - - Public Static voidMain (string[] args) { theTestConstructor test =NewTestConstructor (); - System.out.println (test.value); - System.out.println (test); - } +}
The result of the code execution is:
Constructor1:[email protected]
Constructor2:[email protected]
10
[Email protected]
The visible result is expected, the value assignment is successful, and only one object is created.
Consider the C + + implementation (header file omitted):
1#include"Testconstructor.h"2#include <QDebug>3 4 Testconstructor::testconstructor ()5 {6 //This (ten);7TestConstructor (Ten);8Qdebug () <<"Constructor1:"<< This;9 }Ten OneTestconstructor::testconstructor (intvalue) A { - This->value =value; -Qdebug () <<"Constructor2:"<< This; the}
1#include"Testconstructor.h"2#include <QDebug>3 4 intMainintargcChar*argv[])5 {6TestConstructor *t =NewTestConstructor ();7Qdebug () <<t->value;8Qdebug () <<T;9 DeleteT;Ten}
The result of the code execution is:
Constructor2:0x22fcf0
Constructor1:0xdadfb0
15574896
0xdadfb0
On the one hand, the value set values are not in effect, and on the other hand, two constructors create two different objects, stating that C + + cannot be called from one another in Java-like constructors.
Workaround:
The requirement for most constructors to call each other should be a default parameter, which can be set directly in the function declaration of C + + (Java does not support default parameters) so that no constructor overloads are required:
TestConstructor (int value = 10);
C + + Overloaded constructors cannot be called to each other