你能帮帮我解决这个问题吗?
#include <iostream>
#include <cstring>
using namespace std;
class A
{
public:
char str[4];
A()
{
str = "C++";
cout << "Constructor A" << endl;
}
void display()
{
cout << str << " is your name" << endl;
}
};
int main()
{
A a;
a.display();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给出了以下错误:
**************************Error**********
StringProg.cpp:9: error: ISO C++ forbids initialization of member "str"
StringProg.cpp:9: error: making "str" static StringProg.cpp:9: error: invalid in-class initialization of static data member of non-integral type "char [4]"
StringProg.cpp: In member function "void A::display()":
StringProg.cpp:17: error: "str" was not declared in this scope
**************************
Run Code Online (Sandbox Code Playgroud)
C数组存在很多问题,导致您无法执行您想要执行的操作.
字符串文字的类型为const char[n](字符n长度为+ 1 \0).要在C标准库函数中使用它们,它们会衰减到const char*,它们不具有字符串的大小,并且为了找到它,需要遍历字符串(每个字符都被查看并与之比较\0)
因此,数组赋值运算符需要相当重要; 这不是由语言提供的,您必须使用库函数strcpy来将文字移动到可用内存中.换句话说,您不能像其他值一样分配C数组.
数组以非常原始的方式运行; 它们没有用于比较的运算符,将它们传递给函数并在类中正确存储更加困难.
因此,由于上述所有......
std::string到char[]:class A {
std::string str;
public:
// prefer constructor init list
A() : str("C++") {
// your line would work, too
std::cout << "Constructor A" << std::endl;
}
void display() const {
std::cout << str << " is your name" << std::endl;
}
};
int main()
{
A a;
a.display();
// return 0; is unnecessary
}
Run Code Online (Sandbox Code Playgroud)
一些"经验法则"(拇指规则?):如果您需要多个元素,请从头开始vector<>.永远不要使用C数组.string是一个元素,而不是"字符数组".
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |