我正在阅读“Learn C the Hard Way”一书,并在那里找到了一个看起来像这样的代码片段(下面是我的代码,但程序的结构是相同的):
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string name, int age) {;
this->name = name;
this->age = age;
}
~Person() {
}
};
// When whould I do like this?
class Person *Create_person(string name, int age) {
class Person *person = new Person(name, age);
return person;
};
int main() {
Person *person = Create_person("John", 30);
}
特别看
class Person *Create_person(string name, int age) {
class Person *person = new Person(name, age);
return person;
};
那是什么样的功能?为什么我会这样称呼它,而不仅仅是Person *person = new Person
?它是一个简短的形式
class Person {
public:
Person *Create_person(string name, int age){
Person *person = new Person(name, age);
return person;
}
}
?