c++ - I want to check parameters before puting them into constructor -


in class b want check if n , m bigger 0 , put them constructor of a. how can it?

class a{ private:     int x; int y; public:     a(int x, int y){         this->x=x; this->y=y;     }     void print(){         cout<<x<<" "<<y<<endl;     } };  class b:public a{ public:     b(int n,int m):a(){         ///     } };  

there must more elegant approach this, best i've got right now. can use ternary operator check variables being passed call a's constructor.

#include <iostream>  class { private:     int x; int y; public:     a(int x = 0, int y = 0)     {         this->x = x; this->y = y;     }      void print()     {         std::cout << x << " " << y << "\n";     } };  class b : public { public:     b(int n,int m) : a(          n > 0 && m > 0 ? n : 0,          n > 0 && m > 0 ? m : 0     )     {      } };  int main() {   b b(-1, 1);   b.print();    b b2(1, 1);   b2.print();    b b3(-1, -1);   b3.print(); } 

the output is:

0 0 1 1 0 0 

this approach might frowned upon depending on standard code style, , doesn't take advantage of default values in a's constructor, job done, @ least in simple example.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -