c++ - Define and instantiate C style array of string inside class - Stack Overflow

I am trying to create a class with an array of string defined inside.I want this array of string to be

I am trying to create a class with an array of string defined inside. I want this array of string to be defined when the class is instantiated.

Here is my attempt below (or the code showing my intentions).

class a_class
{
  public:
    static char const *arr_str[];
    int idx;
    void a_function();
  private:
};

a_class MyClass({"aaa", "bbb", "ccc"}, 3);

Obviously the above code does not compile well at all.

How can I achieve this?

I am trying to create a class with an array of string defined inside. I want this array of string to be defined when the class is instantiated.

Here is my attempt below (or the code showing my intentions).

class a_class
{
  public:
    static char const *arr_str[];
    int idx;
    void a_function();
  private:
};

a_class MyClass({"aaa", "bbb", "ccc"}, 3);

Obviously the above code does not compile well at all.

How can I achieve this?

Share Improve this question edited Mar 24 at 20:09 Konrad Rudolph 547k140 gold badges959 silver badges1.2k bronze badges asked Mar 24 at 20:04 NoelNoel 3,9823 gold badges25 silver badges25 bronze badges 7
  • 1 Why do you want a C-style array instead of, let's say, std::vector? C-style array requires knowing its size at compile time. – Dominik Kaszewski Commented Mar 24 at 20:12
  • 1 Also, making the field static means that it is shared across all instances of a_class... – Botje Commented Mar 24 at 20:14
  • Please do not focus too much on the static. This is an error from my part. I need to define the arr_str when instantiating so I can set it differently for each instance created. – Noel Commented Mar 24 at 20:24
  • 1 "I am trying to create a class with an array of string defined inside" - So what you probably actually want is std::vector<std::string> arr_str; I'm guessing. – Jesper Juhl Commented Mar 24 at 20:26
  • Either a vector or std::array<const char *, 3> if you always expect 3 unchangeable strings. You need to state what the actual requirements are -- the code you posted is hard-coded to 3 strings. – PaulMcKenzie Commented Mar 24 at 20:27
 |  Show 2 more comments

3 Answers 3

Reset to default 3

Your array is static, so it is not tied to any specific instance of a_class. You should not be using an instance constructor to initialize it. In modern C++, you can initialize a static class member right in its declaration.

Also, your class does not explicitly define a non-default constructor (ie a constructor that requires arguments be passed in), as such you can't use parenthesis when constructing a new instance of the class while passing in argument values, as your example is doing. The compile will fail with an error about a matching constructor not being found. So, you will have to use curly-braces instead to initialize the non-static member directly.

Try this:

class a_class
{
  public:
    static constexpr char const *arr_str[] = {"aaa", "bbb", "ccc"};
    int idx;
    void a_function();
  private:
};

a_class MyClass{3};

Live Demo

On the other hand, if you want a per-instance array, then it should not be a static member, eg:

template<size_t N>
class a_class
{
  public:
    char const* arr_str[N];
    int idx;
    void a_function();
  private:
};

template<size_t N>
a_class(char const * (&&)[N], int) -> a_class<N>;

a_class MyClass{{"aaa", "bbb", "ccc"}, 3};

Live Demo

Alternatively, use a dynamic-sized std::vector instead of a fixed-sized array, eg:

#include <vector>

class a_class
{
  public:
    std::vector<char const*> arr_str;
    int idx;
    void a_function();
  private:
};

a_class MyClass{{"aaa", "bbb", "ccc"}, 3};

Live Demo

You declared static char const *arr_str[]; inside your class. A static member belongs to the class (not to instances) so every object would share the same array. Also, static data members must be defined outside the class if you plan to initialize them with a value. If you want each instance of your class to hold its own array of strings, the member should be non-static.

Use std::array as follow:

#include <iostream>
#include <array>
#include <string>
#include <initializer_list>
#include <stdexcept>

template <std::size_t N>
class AClass {
public:
    std::array<std::string, N> arr_str;
    int idx;

    // Constructor that accepts an initializer list for exactly N strings and an integer idx
    AClass(std::initializer_list<std::string> init, int i) : idx(i) {
        if (init.size() != N) {
            throw std::invalid_argument("Initializer list must have exactly N elements.");
        }
        std::copy(init.begin(), init.end(), arr_str.begin());
    }
  
    void a_function() {
        std::cout << "Index: " << idx << "\nStrings:";
        for (const auto& s : arr_str) {
            std::cout << " " << s;
        }
        std::cout << std::endl;
    }
};

int main() {
    AClass<3> myClass({"aaa", "bbb", "ccc"}, 3);
    myClass.a_function();
    return 0;
}

I also found an alternative not using std::vector. However this require the use of a global array of string and defining an init function for initialisation.

class a_class
{
  public:
    char **arr_str;
    int idx;
    void a_function();
    void init(char **arr_str);
  private:
};

void a_class::init(char **_arr_str) {
  arr_str = _arr_str;
}

char *global_str[] = {"aaa", "bbb", "ccc"};

int main() {
    a_class MyClass;
    MyClass.init(global_str);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744230281a4564213.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信