C++返回类型为类指针时注意事项
前言
博主很久没有用C++了,最近在用C++时遇到一点小问题,就是在返回类型为类指针时,若该类是在函数中创建,则不能正确返回。问题解决后在这里记录。
开始
step.1 错误代码准备
在VS2017中新建C++控制台应用,并编辑代码如下:
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
int id;
string name;
Student(int i, string n) { id = i; name = n; };
void Say() {
cout << "id=" << id << " ,name=" << name << endl;;
}
};
Student* NewStudent(int i,string n) {
Student s(i, n);
return &s;
}
int main()
{
Student* s = NewStudent(1, "wufan");
s->Say();
system("pause");
}
此时,会看到VS的错误列表显示
按F5运行程序后,可以看到运行结果存在问题:
step.2 正确代码示例
在函数中新建类并返回它的指针时,需要使用new,这样就会正确返回了。
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
int id;
string name;
Student(int i, string n) { id = i; name = n; };
void Say() {
cout << "id=" << id << " ,name=" << name << endl;;
}
};
Student* NewStudent(int i,string n) {
Student* s=new Student(i,n);
return s;
}
int main()
{
Student* s = NewStudent(1, "wufan");
s->Say();
system("pause");
}
结束
C++比起C#、Java等语言,内存的分配回收以及操作指针是需要特别注意的。