c++ - strcpy无法在类中使用字符串指针

标签 c++ string class oop object

我是c++的新手,我制作了一个简单的程序,可根据您的输入来命名类的成员。
但是由于某种原因,编译器会显示此错误-'str': is not a member of 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>',我很难理解它的含义。
请帮帮我
这是我的代码-

#include <iostream>
#include <string>
#include <vector>

class mystring
{
private:
    std::string *str;

public:
    //constructors
    mystring();
    mystring(const std::string &strthing);
    ~mystring();

    //methods
    void display() const;
};


mystring::mystring()                                                    //defalt constructor
    :str(nullptr)
{}

mystring::mystring(const std::string& strthing)                         //copy constructor
    :str(nullptr)
{
    delete str;
    str = new std::string;
    strcpy(this->str, strthing.str);
    std::cout << "overloaded\n";
}
mystring::~mystring()                                                   //destructor
{
    delete [] str;
}

void mystring::display() const                                          //display func
{
    std::cout << *str;
}

int main()
{
    mystring thing;
    mystring object{ "samurai" };
    object.display();

}
我认为重载构造函数中的strcpy()函数出了点问题。
谢谢

最佳答案

strcpy没什么错,但是您的用法没有错。可以使用std::string复制operator=:

 std::string a;
 std::string b;
 a = b;            // copy b to a
另一方面,strcpy用于c字符串,而std::string则不是:
char* strcpy( char* dest, const char* src );
目前尚不清楚为什么要有一个指向std::string的类型指针的成员。您应该使用std::string(无指针),或者如果这是编写自己的字符串类的练习(不是简单的!),那么您应该将数据存储在char数组中。
您得到的错误与strthing.str有关。这里strthing是没有std::string成员的str。如果该构造函数应该是副本构造函数,则应使用const mystring&作为参数,而不是const std::string&

关于c++ - strcpy无法在类中使用字符串指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62715850/

相关文章:

c++ - 在 C++ 中,在 for 循环之外使用 "if"还是在 for 循环中使用 "if"效率更高

c++ - boost::variant for boost::arrays of arbitrary size

javascript - 字符计数器不会打印所有字符

c# List<t> 在一个类中

java - 将值从公共(public)方法传递到私有(private)数组

c++ - Ole 拖放故障排除

C++,使用自己的条件在文件中搜索字符串

C++ 字符串、标点符号、数组

python - 从原始文件外部的类导入函数

c++ - 可以分段的基于散列的数据容器 - C++