c++ - Var members in a class -


i'll try , explain more example. have square , want able initialise variable dimensions such

(width,length) = (int, int) or (double, int) or (double, double) etc..

i know if wanted square have integer sides declare int width , int height how declare can take many forms ?

eg:

header.h

    class square      {         public:             // constructor : initialise dimensions             square();              // set dimensions             template< typename t1, typename t2>             setdim(t1 x, t2 y);          private:             // right ????             template <typename t> t width;             template <typename t> t height;     }; 

moreover, if create square how initialise variables 0.

e.g:

src.cpp

square::square() {     // correct ???     width = 0;     height = 0; } 

it doable, need 2 different types width , height, if understand question correctly (and note rectangle, not square, technically speaking).

#include <iostream>  template <typename w, typename h> class rect {     w width;     h height; public:     rect(const w w, const h h): width(w), height(h) {}     rect(): width(0), height(0) {}     w get_width() { return width; }     h get_height() { return height; } };  template <typename w, typename h> void show_rect(rect<w, h> r) {     std::cout << r.get_width()               << "x"               << r.get_height()               << "="               << r.get_width() * r.get_height()               << std::endl; }  int main() {     show_rect(rect<int, int>{});     show_rect(rect<double, long>{0.3, 8}); } 

you can see how can overload constructor initialize default values. see how can write function takes object of class argument.

with this, get:

$ make rect g++ -std=c++14 -pedantic -wall -o2    rect.cpp   -o rect $ ./rect 0x0=0 0.3x8=2.4 

but not sure wisdom of doing this. sure explain in comments :)


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -