c++ - can i initiate an object of a class through a statement? -
as understand can initiate object s of class sample through statement,
sample s=10;
compiler treat statement sample s(10)
. if there 1 argument constructor in class sample , statement work if there no 1 argument constructor compiler flash error.
i want know. can initiate object of class sample through statement,
sample s=10,20;
this shown in following example:
class sample { private: int a,b; public: sample(int i) { a=i; b=i; } sample(int i, int j) { a=i; b=j; } void display(){ cout<<a<<endl<<b; } }; void main(){ sample s = 10; sample c = 10,20; c.display(); }
would above program work?
sample c = 10,20;
this not compiled. note ,
here not operator declaration separator , expects sample c = 10, d = 20
sample c = (10,20);
,
operator executed , 10 , 20 evaluated respectively later result. statment equivalent sample s(20);
would above program work?
it not compile.
sample c = (10,20)
compile , run not call constructor 2 arguments might expect.
can initiate object of class through statement?
yes, use sample c(10, 20)
in c++11 onwards, syntax sample c = {10, 20}
possible using std::initializer_list
constructor argument.
sample(std::initializer_list<int> l) : a(0), b(0) { if(l.size() > 2u) { /* throw */ } int = 0; for(int x : l) { if(i == 0) { = x; b = x; } else if(i == 1) b = x; ++i; } } ... sample c = {10,20};
Comments
Post a Comment