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

Dan*_*nte 0 c++ string strcpy

我收到这个错误:

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

我假设它意味着它无法将我的一个标题字符串分配给我的newtitle字符串,因为它们的类型不同.(我认为一个是char和另一个const char?)

strcpy(title, newtitle);
Run Code Online (Sandbox Code Playgroud)

但它们都被定义为类型字符串,所以我有点困惑的是它给了我这个错误是什么.虽然我错误地认为这个错误意味着什么.

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


}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 6

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

你并不需要使用strcpystd::string,你可以只

title = newtitle;
Run Code Online (Sandbox Code Playgroud)

  • @Dante,你不能使用`strcpy`将`std :: string`复制到`std :: string`中.你应该使用`char`数组吗? (2认同)
  • @songyuanyao很有可能,只是不是一个好主意.你可以写`d.resize(strlen(ptr)+ 1); strcpy(&d [0],ptr); d.resize(d.size() - 1);` (2认同)