gpt4 book ai didi

c++ - 错误 : no member function declared in class

转载 作者:搜寻专家 更新时间:2023-10-31 00:55:27 27 4
gpt4 key购买 nike

我的代码中不断出现以下错误:

(第 58 行)错误:没有在类“Person”中声明的“std::string Person::Modify_Person(Person)”成员函数在函数“int main()”中:

(第 113 行)错误:“Modify_Person”未在此范围内声明

代码如下:

#include <iostream>
#include <string>

using namespace std;

void PassByByValue(int num2){

cout << "You are in PassByValue()" << endl;

num2++;

}
class Person{
int age;
string name;
int height;
int weight;
public:

Person(){

}

Person(string name){
this->name=name;
}

string getName(){
return this->name;
}

void setAge(int age){
this->age=age;
}


void setName(string name){
this->name=name;
}

void setHeight(int height){
this->height=height;
}

void setWeight(int weight){
this->weight=weight;
}


~Person(){

}

};



string Person::Modify_Person(Person example){

example.getName()="Jessica";

return example.getName();
}

void PassByRef(int& num3){

cout << "You are in PassByRef()" << endl;

num3=50;

cout << "inside PassByRef() pNum is: " <<num3<<endl;

}

int main()
{
int num1;
int* pNum;

num1=3;
*pNum=5;

PassByByValue(num1);

cout << "num1= " <<num1 <<endl;

PassByRef(*pNum);

cout << "outside PassByRef() in main() pNum is: " <<pNum<<endl;

PassByByValue(*pNum);

double* DblePtr;

DblePtr= new double;

*DblePtr=12.0;

cout<< "DblePtr: "<< &DblePtr;

delete[] DblePtr;

cout<< "DblePtr: "<< &DblePtr;

Person human;
human.setName("Kate");
human.setAge(27);
human.setHeight(100);
human.setWeight(100);

Modify_Person(human);

cout << "Modify_Person returns: " << Modify_Person(human) <<endl;

cout << "name should be Jessica: " << human.getName() << endl;

return 0;
}

最佳答案

您不能在 C++ 中的类外部声明成员函数。要解决此问题,请将相应的成员函数声明添加到您的类中:

class Person{
...
public:
string Modify_Person(Person);
};

然后你的代码就可以工作了。另外,一个建议:如果构造函数和析构函数为空,则不要定义它们;允许编译器为您生成它们。如果您打算通过这样做来禁用移动构造函数等,请编写 Person() = default; 让编译器生成默认实现。

关于c++ - 错误 : no member function declared in class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41885108/

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