簡體   English   中英

c++ 如何在構造函數中初始化 char

[英]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;    

    } 

我不能使用string ,因為我被告知不要,因此,我需要知道如何使它顯示所需的 output

要復制字符串,您必須使用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;
    }
};

如何在構造函數中初始化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. 使用<algorithm>中的std::copy
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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM