Home > OS >  Is there any way my class take input value like array in C ?
Is there any way my class take input value like array in C ?

Time:12-26

I want write a class and take input value like array

int arr[] = {1,2,3,4}
myFunc f = {a,b,c,d};

Is there any way my class take input value like array in C ?

CodePudding user response:

This is what std::initializer_list is for:

#include <vector>
#include <iostream>

class foo {
private:
    std::vector<int> nums_;
public:
    foo(std::initializer_list<int> init) :
        nums_(init.begin(), init.end())
    {}

    void display() {
        for (auto n : nums_) {
            std::cout << " " << n;
        }
        std::cout << "\n";
    }
};

int main()
{
    foo f = { 1,2,3,4 };
    f.display();
    return 0;
}

CodePudding user response:

You could try and pass a pointer to an array, as an example:

class B
{
public:
    B(int* arr, const size_t len)
    {
        // Bad way:
        // this->arr = arr;
        // this->len = len;
        
        // Better:
        this->arr = new int[len];
        this->len = len;
        
        for (int i = 0; i < len; i  )
        {
            this->arr[i] = arr[i];
        }
    }
    
    void printArray() const 
    {
        for (int i = 0; i < this->len; i  )
        {
            std::cout << this->arr[i] << " ";
        }
        
        std::cout << std::endl;
    }
    
    int* arr;
    size_t len;
};


int main()
{
    int* arr = new int[10];
    
    for (int i = 0; i < 10; i  )
    {
        arr[i] = i   1;
    }
    
    B b(arr, 10);
    
    b.printArray();
    
    delete[] arr;

    return 0;
}

But the problem is that it's not memory safe and not so useful since CPP's standard library provides better solutions. For example, you might use std::vector

  • Related