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

编程入门 行业动态 更新时间:2024-10-27 01:27:25
本文介绍了如何在构造函数中初始化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数组?

本文发布于:2023-07-30 11:08:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1248852.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   初始化   函数   如何在   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!