简体   繁体   中英

c++ How to initialize char in 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;    

    } 

I cannot use string because I'm told not to, therefore, I need to know how I can make it such that it displays the desired output

To copy a string you have to use std::strcpy , not str[848] = a[848] .

str[848] = a[848] copy only one element, but in your case it's a mistake, becasue your array has indexes [0, 847].

Try

class MyClass
{
    private :
    char str[848];

    public :

    MyClass()
    {

    }

    MyClass(char a[])  
    {
        std::strcpy(src, a);
    }

    MyClass operator () (char a[])
    {
        std::strcpy(src, a);
    }

    void myFunction(MyClass m)
    {

    }

    void display()
    {
        cout << str;
    }
};

How to initialize char array in constructor?

  1. Use a loop to copy element by element:
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];
    }
}
  1. Use std::copy from <algorithm>
const int size = 848;
std::copy(a, a + size, str); 

Prefer std::copy over strcpy , if you have to use strcpy , prefer strncpy instead. You can give size to it, so it can help prevent errors and buffer overflows.

MyClass(char a[])  
{
    strncpy(str, a, sizeof(str));
}
  1. Use std::array from the library. It has various advantages, for eg you can directly assign it like normal variables. Example:
std::array<char, 848> str = {/*some data*/};
std::array<char, 848> str1;
str1 = str;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM