C++我的练习代码中的代码错误

C++ code error in my practice code

本文关键字:代码 错误 C++ 练习 我的      更新时间:2023-10-16

你能帮我解决这个问题吗?

#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;
}

它给出以下错误:

**************************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
**************************

C 数组有很多问题会阻止你做你想做的事情。

  • 字符串文本的类型为 const char[n](n 是它们的长度 + 1 表示字符(。要在 C 标准库函数中使用它们,它们衰减为 const char* ,不携带字符串的大小,为了找到它,需要遍历字符串(查看并与比较的每个字符(

  • 因此,数组赋值运算符需要相当不平凡;这不是语言提供的,你必须使用像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
}
一些"经验法则

"(经验法则?(:如果您需要多个元素,请从vector<>开始。切勿使用 C 数组。 string是一个元素,而不是"字符数组"。

尝试以下操作

#include<iostream>
#include<cstring>
class A
{
private:
    char str[4];
public:
    A() : str { "C++" }
    {
        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;
}

程序输出为

Constructor A
C++ is your name

考虑到数组没有复制赋值运算符。因此,您的程序中的此语句

str = "C++';

即使更新错别字并写

str = "C++";

无效。

您可以使用在标头 <cstring> 中声明的标准 C 函数strcpy。例如

    #include <cstring>
    //...
    A()
    {
        std::strcpy( str, "C++" );
        std::cout << "Constructor A" << std::endl;
    }