我怎么能初始化在构造函数中字符数组? [英] How can I initialize char arrays in a constructor?

查看:350
本文介绍了我怎么能初始化在构造函数中字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有麻烦声明和初始化字符数组。它始终显示随机字符。我创建了code更小一点,以显示我想要在我的大程序:

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

和抱歉,如果我的格式是坏的,我勉强可以弄清楚这个网站更不用说如何解决我的code:(

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

推荐答案

如果有不使用的std ::字符串没有特别的理由,不要使用的std ::字符串

If there are no particular reasons to not use std::string, do use 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();
}

这篇关于我怎么能初始化在构造函数中字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆