How can I initialize char arrays in a constructor?(如何在构造函数中初始化 char 数组?)
问题描述
我在声明和初始化 char 数组时遇到问题.它总是显示随机字符.我创建了一小段代码来展示我在更大的程序中尝试的内容:
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 :(
推荐答案
如果没有特殊原因不使用std::string
,请使用std::string
.
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();
}
这篇关于如何在构造函数中初始化 char 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在构造函数中初始化 char 数组?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01