gpt4 book ai didi

C++如何在函数中传递字符串数组并分配给变量?

转载 作者:行者123 更新时间:2023-11-28 04:44:14 24 4
gpt4 key购买 nike

我在编写一个简单的函数时遇到了这个错误。这是我的功能规范。

string studentName;
string courseTaken[3];
void setStudent(string, string[]);

void Student::setStudent(string n, string a[])
{
studentName= n;
courseTaken = a;
}

这是我得到的错误:

incompatible types in assignment of string* to string [3] on this line courseTaken = a;

在我的代码中,我从未声明过任何指针或字符。

我不太明白这里出了什么问题。

最佳答案

您不能使用 = 运算符将字符串数组 string a[] 分配给数组 courseTaken。表达式 string a[] 等同于 std::string*。这就是您收到编译器错误的原因。

这可能是你想要的:

#include <iostream>
using namespace std;

class Student
{
public:
string studentName;
string courseTaken[3];
void setStudent(string n, string a[]);
};

void setStudent(string n, string a[]);

void Student::setStudent(string n, string a[])
{
studentName = n;
for(int i=0; i < sizeof(courseTaken)/sizeof(courseTaken[0]); i++)
courseTaken[i] = a[i];
}

int main()
{
Student student;

string courses[3] = {"Cobol","C++","Fortran"};
student.setStudent("Eva", courses);

for (int i = 0; i < 3; i++){
cout << student.courseTaken[i] << endl;
}

return 0;
}

输出:

Cobol                                                                                                                                        
C++
Fortran

关于C++如何在函数中传递字符串数组并分配给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com