C++ 如何在构造函数中初始化字符数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10422487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:02:40  来源:igfitidea点击:

How can I initialize char arrays in a constructor?

c++arrayschar

提问by ShengLong916

I'm having trouble declaring and initializing a char array. It always displays random characters. I created a smaller bit of code to show what I'm trying in my larger program:

我在声明和初始化字符数组时遇到问题。它总是显示随机字符。我创建了一小段代码来显示我在更大的程序中尝试的内容:

class test
{
    private:
        char name[40];
        int x;
    public:
        test();
        void display()
        {
            std::cout<<name<<std::endl;
            std::cin>>x;
        }
};
test::test()
{
    char name [] = "Standard";
}

int main()
{   test *test1 = new test;
    test1->display();
}

And sorry if my formatting is bad, I can barely figure out this website let alone how to fix my code :(

对不起,如果我的格式不好,我几乎无法弄清楚这个网站更不用说如何修复我的代码了:(

回答by Cheers and hth. - Alf

If there are no particular reasons to not use std::string, do use std::string.

如果没有不使用的特殊原因std::string,请使用std::string

But if you really need to initialize that character array member, then:

但是如果你真的需要初始化那个字符数组成员,那么:

#include <assert.h>
#include <iostream>
#include <string.h>
using namespace std;

class test
{
    private:
        char name[40];
        int x;
    public:
        test();
        void display() const
        {
            std::cout<<name<<std::endl;
        }
};

test::test()
{
    static char const nameData[] = "Standard";

    assert( strlen( nameData ) < sizeof( name ) );
    strcpy( name, nameData );
}

int main()
{
    test().display();
}

回答by Mark Ransom

Your constructor is not setting the member variable name, it's declaring a local variable. Once the local variable goes out of scope at the end of the constructor, it disappears. Meanwhile the member variable still isn't initialized and is filled with random garbage.

您的构造函数没有设置成员变量name,而是声明了一个局部变量。一旦局部变量在构造函数结束时超出范围,它就会消失。与此同时,成员变量仍未初始化,并充满了随机垃圾。

If you're going to use old-fashioned character arrays you'll also need to use an old-fashioned function like strcpyto copy into the member variable. If all you want to do is set it to an empty string you can initialize it with name[0] = 0.

如果您打算使用老式字符数组,您还需要使用老式函数,例如strcpy复制到成员变量中。如果您只想将其设置为空字符串,您可以使用name[0] = 0.

回答by mfontanini

Considering you tagged the question as C++, you should use std::string:

考虑到您将问题标记为 C++,您应该使用std::string

#include <string>

class test
{
    private:
        std::string name;
        int x;
    public:
        test();
        void display()
        {
            std::cout<<name<<std::endl;
            std::cin>>x;
        }
};
test::test() : name("Standard")
{

}

回答by sehe

Since you are using C++, I suggest using strings instead of char arrays. Otherwise you'd need to employ strcpy (or friends).

由于您使用的是 C++,我建议使用字符串而不是字符数组。否则你需要使用 strcpy (或朋友)。

Also, you forgot to delete the test1 instance.

另外,您忘记删除 test1 实例。

#include <iostream>
#include <string>

class test
{
    private:
        std::string name;
        int x;
    public:
        test();
        void display()
        {
            std::cout<<name<<std::endl;
        }
};

test::test()
{
    name = "Standard";
}

int main()
{   
    test test1;
    test1.display();

    std::cin>>x;
}

回答by Jonathan Mee

c++11actually provides two ways of doing this. You can default the member on it's declaration line or you can use the constructor initialization list.

c++11实际上提供了两种方法来做到这一点。您可以在其声明行中默认该成员,也可以使用构造函数初始化列表。

Example of declaration line initialization:

声明行初始化示例:

class test1 {
    char name[40] = "Standard";
public:
    void display() { cout << name << endl; }
};

Example of constructor initialization:

构造函数初始化示例:

class test2 {
    char name[40];
public:
    test2() : name("Standard") {};
    void display() { cout << name << endl; }
};

You can see a live example of both of these here: http://ideone.com/zC8We9

您可以在此处查看这两个示例:http: //ideone.com/zC8We9

My personal preference is to use the declaration line initialization because:

我个人的偏好是使用声明行初始化,因为:

  1. Where no other variables must be constructed this allows the generated default constructor to be used
  2. Where multiple constructors are required this allows the variable to be initialized in only one place rather than in all the constructor initialization lists
  1. 在不需要构造其他变量的情况下,这允许使用生成的默认构造函数
  2. 在需要多个构造函数的情况下,这允许变量仅在一个地方初始化,而不是在所有构造函数初始化列表中


Having said all this, using a char[]may be considered damaging as the generated default assignment operator, and copy/move constructors won't work. This can be solved by:

说了这么多,使用 achar[]作为生成的默认赋值运算符可能被认为是有害的,并且复制/移动构造函数将不起作用。这可以通过以下方式解决:

  1. Making the member const
  2. Using a char*(this won't work if the member will hold anything but a literal string)
  3. In the general case std::stringshould be preferred
  1. 制作会员 const
  2. 使用 a char*(如果成员将持有除文字字符串以外的任何内容,则这将不起作用)
  3. 在一般情况下std::string应该是首选