Was sagt der ISO-Standard zu "Konstruktor(int a) : a(a) {}"?
-
Hi!
Auf der Suche nach einem möglichst einfachen Weg, Membervariablen einer Klasse zu initialisieren, bin ich auf die Idee gekommen den Konstruktorparameter genauso zu nennen wie die zu initialisierende Variable, z.B. a und a.
Meine Frage ist das konform zum C++ ISO Standard? Wer kann dazu was sagen?
In
- Stroustrup, "Die C++ Programmiersprache"
- Breymann, "C++ Eine Einführung"
hab ich nix dazu gefunden!lg,
NoutroProgrammbeispiel (läuft mit Dev C++ (also mit GNU C++)):
#include <iostream>
using namespace std;
class Test
{
public:
Test(int a) : a(a) {}
int get() { return a; }
private:
int a;
};int main(int argc, char *argv[])
{
Test tst(147);
cout << tst.get() << endl;system("PAUSE");
return 0;
}
-
ich fände es genau so einfach, den parameter b zu nennen..
#include <iostream> using namespace std; class Test { public: Test(int b) : a(b) {} int get() { return a; } private: int a; }; int main() { Test tst(2); cout << tst.get() << endl; }
achtung: folgendes geht aber nicht :
#include <iostream> using namespace std; class Test { public: Test(int a) { a=a; } int get() { return a; } private: int a; }; int main() { Test tst(2); cout << tst.get() << endl; }
dann nur mit
this->a=a;
<edit> java hatte mich eingeholt</edit>
-
12.6.2p2 "Names in a mem-initializer-id are looked up in the scope of the constructor's class and, if not found in that scope, are looked up in the scope containing the constructor's definition.[...]"
12.6.2p7 "Names in the expression-list of a mem-initializer are looked up in the scope of the constructor for which the mem-initializer is specified."
Also ja, das ist konform, falls das noch nicht klar geworden sein sollte
-
Thank you very much, Bashar!