Kann ich Standardwerte wie in METHOD 1 auf einmal angeben oder soll ich einen überladenen Konstruktor wie in METHOD 2 oder mit Initialisierungsliste wie in METHOD 3/4 verwenden?Standardwerte von Argumenten im C++ - Konstruktor
Welche Methode ist besser/richtiger Weg und warum (alle scheinen zu funktionieren)?
Und was ist der Unterschied zwischen METHODE 3 und 4 - sollte ich zuerst Konstruktor Deklaration angeben, und dann nächste Definition außerhalb der Klasse oder kann ich sofort die Definition angeben?
Methode 1:
#include <iostream>
#include <string>
using namespace std;
const string GLOBAL_VAR = "XXX";
class Object
{
private:
string var;
public:
Object(string inArg = "yyy")
{
this->var = GLOBAL_VAR + inArg + "ZZZ";
}
string show()
{
return this->var;
}
};
int main() {
Object o1, o2("www");
cout << o1.show() << endl;
cout << o2.show() << endl;
system("pause");
}
Methode 2:
#include <iostream>
#include <string>
using namespace std;
const string GLOBAL_VAR = "XXX";
class Object
{
private:
string var;
public:
Object()
{
this->var = GLOBAL_VAR + "yyyZZZ";
}
Object(string inArg)
{
this->var = GLOBAL_VAR + inArg + "ZZZ";
}
string show()
{
return this->var;
}
};
int main() {
Object o1, o2("www");
cout << o1.show() << endl;
cout << o2.show() << endl;
system("pause");
}
Methode 3:
#include <iostream>
#include <string>
using namespace std;
const string GLOBAL_VAR = "XXX";
class Object
{
private:
string var;
public:
//declaration:
Object();
Object(string);
string show()
{
return this->var;
}
};
//definition:
Object::Object() : var(GLOBAL_VAR + "yyyZZZ") {}
Object::Object(string inArg) : var(GLOBAL_VAR + inArg + "ZZZ"){}
int main() {
Object o1, o2("www");
cout << o1.show() << endl;
cout << o2.show() << endl;
system("pause");
}
VERFAHREN 4:
#include <iostream>
#include <string>
using namespace std;
const string GLOBAL_VAR = "XXX";
class Object
{
private:
string var;
public:
//declaration and definition in one:
Object() : var(GLOBAL_VAR + "yyyZZZ") {}
Object(string inArg) : var(GLOBAL_VAR + inArg + "ZZZ") {}
string show()
{
return this->var;
}
};
int main() {
Object o1, o2("www");
cout << o1.show() << endl;
cout << o2.show() << endl;
system("pause");
}
In C++ benötigen Sie nicht die Notation 'this->'. Greifen Sie direkt auf die Mitgliedsvariablen zu. –
Es gibt wirklich keinen Unterschied zwischen Methode 2 und 3. Und der einzige Unterschied zwischen Methode 2 und 4 ist, dass man Initialisierungslisten verwendet, während die andere nicht. Das heißt, die Methoden 2, 3 und 4 sind gleich. Was "das Beste" ist, das ist das, was du denkst, es ist subjektiv und eine Frage der Meinung. –