c++ - 如何在构造函数中初始化char

标签 c++ arrays constructor

    #include <iostream>
    using namespace std;

    class MyClass
    {
        private :
        char str[848];

        public :

        MyClass()
        {

        }

        MyClass(char a[])  
        {
            str[848] = a[848];
        }

        MyClass operator () (char a[])
        {
            str[848] = a[848];
        }

        void myFunction(MyClass m)
        {

        }

        void display()
        {
            cout << str[848];
        }
    };

    int main()
    {   
        MyClass m1;  //MyClass has just one data member i.e. character array named str of size X
                                //where X is a constant integer and have value equal to your last 3 digit of arid number
        MyClass m2("COVID-19") , m3("Mid2020");
        m2.display(); //will display COVID-19
        cout<<endl;
        m2.myFunction(m3);
        m2.display(); //now it will display Mid2020
        cout<<endl;
        m3.display(); //now it will display COVID-19
      //if your array size is even then you will add myEvenFn() in class with empty body else add myOddFn()
      return 0;    

    } 

我不能使用string,因为有人告诉我不要这样做,因此,我需要知道如何制作它才能显示所需的输出

最佳答案

如何在构造函数中初始化char数组?

  • 使用循环逐元素复制元素:
  • MyClass(char a[])  
    {
        //make sure that sizeof(a) <= to sizeof(str);
        // you can not do sizeof(a) here, because it is
        // not an array, it has been decayed to a pointer
    
        for (int i = 0; i < sizeof(str); ++i) {
            str[i] = a[i];
        }
    }
    
  • 使用std::copy中的<algorithm>
  • const int size = 848;
    std::copy(a, a + size, str); 
    

    如果需要使用std::copy,则首选strcpy而不是strcpy,而不是strncpy。您可以为其提供大小,以帮助防止错误和缓冲区溢出。
    MyClass(char a[])  
    {
        strncpy(str, a, sizeof(str));
    }
    
  • 使用库中的std::array。它具有多种优势,例如,您可以像普通变量一样直接分配它。示例:
  • std::array<char, 848> str = {/*some data*/};
    std::array<char, 848> str1;
    str1 = str;
    

    关于c++ - 如何在构造函数中初始化char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62382187/

    相关文章:

    c++ - C 中的链接器错误 : undefined Reference to "method" c

    C++ 类构造函数限定为 __attribute__((pure)) 或 __attribute__((const))

    php - 缩短连续数字之间带有连字符的数字列表

    Javascript 数组构造函数问题

    c++ - 通过构造函数在类中初始化二维数组

    c++ - 在数组 C++ 中插入整数

    c++ - 两种函数作为参数传递方式的区别

    arrays - 在 Swift 中保留一组自定义结构

    Javascript位置变量更改网页地址

    java - 为什么 Java Bean 模式不是线程安全的