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

问题描述 投票:1回答:2
    #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,因为有人告诉我不要这样做,因此,我需要知道如何制作它才能显示所需的输出

c++ arrays constructor
2个回答
1
投票

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

  1. 使用循环逐个元素复制:
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. 使用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));
}
  1. 使用库中的std::array。它具有多种优势,例如,您可以像普通变量一样直接分配它。示例:
std::array<char, 848> str = {/*some data*/};
std::array<char, 848> str1;
str1 = str;

1
投票

要复制字符串,您必须使用std::strcpy,而不是str[848] = a[848]

[str[848] = a[848]仅复制一个元素,但由于您的数组具有索引[0,847]。在您的情况下,这是一个错误。

尝试

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;
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.