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

时间:2012-05-02 22:17:14

标签: c++ arrays char

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

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();
}

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

5 个答案:

答案 0 :(得分:9)

如果没有特别的理由不使用std::string,请使用std::string

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

#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();
}

答案 1 :(得分:6)

您的构造函数未设置成员变量name,它声明了一个局部变量。一旦局部变量超出构造函数末尾的范围,它就会消失。同时,成员变量仍未初始化,并且随机垃圾填充。

如果你要使用老式的字符数组,你还需要使用像strcpy这样的老式函数来复制到成员变量中。如果您只想将其设置为空字符串,则可以使用name[0] = 0初始化它。

答案 2 :(得分:5)

考虑到您将问题标记为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")
{

}

答案 3 :(得分:4)

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

此外,您忘记删除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;
}

答案 4 :(得分:3)

实际上提供了两种方法。您可以在其声明行上默认成员,也可以使用构造函数初始化列表。

声明行初始化的示例:

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

构造函数初始化的示例:

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

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

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

  1. 如果不构造其他变量,则允许使用生成的默认构造函数
  2. 如果需要多个构造函数,这允许变量只在一个地方而不是在所有构造函数初始化列表中初始化
  3. 说完这一切之后,使用char[]可能会被视为有害,因为生成的默认赋值运算符和复制/移动构造函数将无法工作。这可以通过以下方式解决:

    1. 使成员const
    2. 使用char*(如果该成员除了文字字符串之外只保留任何内容,这将无效)
    3. 一般情况下,std::string应该是首选
相关问题