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

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

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

最佳答案

如果没有特殊原因不使用 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();
}

关于c++ - 如何在构造函数中初始化 char 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10422487/

相关文章:

来自 Int 的 C# Char 用作 String - VB Chr() 的真正等价物

c - 从指针数组中查找重复项

c++ - 套接字数据的十六进制表示(char)c++

c++ - 这种用于创建异构仿函数容器的技术能否得到挽救?

c++ - Netbeans 8.1(用于 C/C++)找不到我的编译器(gcc-6.0.0 开发版)

c - 为什么 printf 打印一个未作为参数传递的变量?

javascript - jQuery/JavaScript : Filter array with another array

c++ - 从字符串中删除重复的字符

c++ - 如何更改转储的 VCD 文件的时间刻度?

c++ - 迭代 boost::python vector_indexing_suite 出现意外结果