开发者

Constructor with default values & Different Constructors

开发者 https://www.devze.com 2023-04-04 21:31 出处:网络
I would like to do something like this class foo{ private: double a,b; public: foo(double a=1, double b=2){

I would like to do something like this

class foo{
private:
    double a,b;

public:
    foo(double a=1, double b=2){
        this.a=a;
        this.b=b;
    }
}

int main(){
    foo first(a=1);
    foo first(b=2);
}

Is such thing possible or do I need to create two new constructors?

Here comes the 2. question: What is the difference in those two constructors:

class foo{
private:
 开发者_StackOverflow   int a;

public:
    foo(int in):a(in){}
}

or

class foo{
private:
    int a;

public:
    foo(int in){a=in}
}


foo first(a=1);
foo first(b=2);

You cannot really have this in C++. It was once considered for standarization but then dropped. Boost.Parameter does as much as it can to approximate named parameters, see http://www.boost.org/doc/libs/1_47_0/libs/parameter/doc/html/index.html

foo(int in):a(in){}
foo(int in){a=in}

The first constructor is initializating a, while the second is assigning to it. For this particular case (int) there isn't much of a difference.


In C++, the this pointer is a pointer not an object (in java, you would access it with the .). That said, you would need a dereferencing arrow (i.e. this->member or (*this).member).

In any case, this can be done. However, parameterization in C++ works in reverse order and cannot be named. For instance, int test(int a=2, int b=42) is legal as well as int test(int a, int b=42). However, int test(int a=2, b) is not legal.

As for your second question, there is no significant difference between the constructors in this example. There are some minor (potential) speed differences, but they are most-likely negligible in this case. In the first one you are using an initializer list (required for inheritance and calling the constructor of the base class if need be) and the second one is simply explicitly setting the value of your variable (i.e. using operator=()).


It's probably overkill for your example, but you might like to learn about the Named Parameter Idiom.


C++ doesn't support named parameters so this:

int main()
{ 
  foo first(a=1); 
  foo first(b=2); 
} 

Is not legal. You also have multiple non-unique idenfiers (e.g. first).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号