Initialize arrays of characters in a class

When I compile the code below with g ++ 4.8.2, I get an error message.

#include <iostream>

using namespace std;

class test {
public:
    void print() {
        cout << str << endl;
    }

private:
    char str[] = "123456789"; // error: initializer-string for array of chars
                              // is too long
};

int main() {
    char x[] = "987654321";
    cout << x << endl;

    test temp;
    temp.print();
}

Why did I get this error, what is the difference between strclass testand xfunction main?

+4
source share
6 answers

Inside your class, you must explicitly specify the size of the array:

class test {
...
private:
    // If you really want a raw C-style char array...
    char str[10] = "123456789"; // 9 digits + NUL terminator
};

Or you can just use std::string(which, it seems to me, in C ++ code is much better than using raw C-style strings):

#include <string>
...

class test {
...
private:
    std::string str = "123456789"; 
};
+9
source

You cannot have arrays of unknown size in structures / classes, you need to set the size of the array.

, std::string . , .

+2

, , . . /, . .

.

:

class Test
{
   public:
        int num;    //You don't intialie value here
};

int main
{
       Test testObj();
       testObj.num = 100;
}

, private, . exmaple setNum()

.

class Test
{
   public:
        Test(int);  //Constructor
   private:
        int num;    //You don't intialie value here
};


Test::Test(int value)
{
    this -> num = value;
}

int main
{
    Test testObj(100); //set num to 100
}

- , , , , setNum() .

testObj.setNum(100);

, char [], int. . int, char [], . , , char [] char *. .

+1

, , const char *str = "123456789";

0

char. , , . , , .

0

The difference is

class foo {

    class y;  // Instance Variable

    void foo(){
        class x;  // Method Variable
        // use x and y
    }
}

The instance variable char*will work char* x = "foobar". A compiler, possibly allowing a method variable to be set to char[], because the scope is limited. I am trying to find some kind of literature to explain the different treatment.

0
source

Source: https://habr.com/ru/post/1535595/


All Articles