When I developed C#, I used it like the code below, but I wonder how I do it in C++. I wrote this() to call out the class name, but it says no Why?
class Test {
public:
Test() {
//DoSomething
}
Test(int count) : this() {
//DoSomething
}
Test(int count, string name) : this(count) {
//DoSomething
}
};
In C++11 and above, you can call another constructor within the constructor The grammar is a bit different from C#.
class Test {
public:
Test() {
//DoSomething
}
Test(int count) : Test() {
//DoSomething
}
Test(int count, string name) : Test(count){
//DoSomething
}
};
You can write it like this.
If you use C++03, the code above is not supported To be similar, there are the following ways:
class Test {
public:
//Test(int) and Test(int, string) support
Test(int count, string name=NULL){
//DoSomething
}
};
class Test {
public:
Test() {
init();
}
Test(int count) : Test() {
init(count);
}
Test(int count, string name=NULL){
init(count, name);
}
private:
void init() {}
void init(int count) { init(); }
void init(int count, string name) { init(count); }
};
© 2024 OneMinuteCode. All rights reserved.