如果我分配给彼此的两个变量都是字符串类型,为什么我会收到这个strcpy赋值错误

Why am I receiving this strcpy assignment error if the two variables I am assigning to each other are both of type string?

本文关键字:为什么 类型 字符串 赋值 错误 strcpy 变量 分配 如果 两个      更新时间:2023-10-16

我收到这个错误:

error: cannot convert 'std::string {aka std::basic_string<char>}' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)'

我认为这意味着它无法将我的一个标题字符串分配给我的新标题字符串,因为它们不属于同一类型。(我想一个是char,另一个是const char?)

strcpy(title, newtitle);

但它们都被定义为类型字符串,所以我有点困惑是什么导致了这个错误。尽管我对这个错误的确切含义可能是错的。

#include<iostream>
#include<iomanip>
using namespace std;
#include <cstring>

class Movie{
private:
string title;
int year;
string director;
public:
void setTitle(string);  // function prototype
void setYear(int);  // function prototype
void setDirector(string);   // function prototype
void displayMovie();    // function prototype
};

void Movie::setTitle(string newtitle)   
{
strcpy(title, newtitle);    
}

int main()
{
Movie myMovie;
string movietitle;

cout << "Enter the title of the Movie: " << endl;
cin >> movietitle;
myMovie.setTitle(movietitle);

}

std::strcpy期望其第一个参数为char*,但std::string无法隐式转换为char*,这就是编译器抱怨的原因。

std::string不需要使用strcpy,只需即可

title = newtitle;