Форум » C/C++ для начинающих (C/C++ for beginners) » how can i pass a ar.. » Ответить

how can i pass a ar..

ramees: how can i pass a array into class and dispaly array throgh accessor function

Ответов - 5

Сыроежка: What do you mean saying "pass an array to a class"? Could you show some code that demonstrates the idea and what you are going to do?

ramees: for example int main(){ string name; int height ; double weight; cout<<"enter your name "<<endl; cin>>name; cout<<"enter your height "endl; cin>>height; cout<<"enter your weight"<<endl; cin>>weight; BMI student_1(name, height,weight); return 0; } u can see above code that pass all three data into BMI student_1 object . i like to pass an array like this how can i do that

Сыроежка: Thet is instead of passing only three scalar values to the constructor you would want to pass an array of these scalar values as the argument of the constructor, would not you? If so then you could define an array of structure [pre2] struct Person { std::string name; int height; double weight; } a[SOME_SIZE]; [/pre2] Or you could use an array of tuples. For example [pre2] #include <iostream> #include <string> #include <tuple> void f( const std::tuple<std::string, int, double> a[], size_t n ) { for ( size_t i = 0; i < n; i++ ) { std::cout << std::get<0>( a ) << " has height equal to " << std::get<1>( a ) << " and weight equal to " << std::get<2>( a ) << std::endl; } } int main() { std::tuple<std::string, int, double> a[] = { std::make_tuple( "Peter", 176, 70.5 ), std::make_tuple( "Bob", 183, 80 ) }; f( a, sizeof( a ) / sizeof( *a ) ); return 0; } [/pre2] The output is [pre2] Peter has height equal to 176 and weight equal to 70.5 Bob has height equal to 183 and weight equal to 80 [/pre2] If you want something different then you should provide a more detailed descrription.


ramees: i need to do sum calculation on a 1D array so i decide to create a class and do the calculation in side the class and get the output from the class through accessor function . i like to know how do this in class

Сыроежка: If the size of the array is fixed you can define a data member of the class either as an array or an object of type std::array. You can also overload the subscript operator (operator []) to access elements of this data member. In this thread at stackoverflow I showed how the data member can be initialized in constructors. If the size of the array is not fixed then you should dynamically allocate memory. In this case you can use standard container std::vector as a data member of the class.



полная версия страницы