小编Kar*_*tty的帖子

使用和不使用 new 关键字创建 C++ 对象

使用 new 关键字创建对象:

#include <iostream>
#include <string>

using namespace std;

class Person {
  private:
  string name;

  public:
  Person(string name) {
    setName(name);
  }

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

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

int main() {
  Person *person1 = new Person("Rajat");
  Person *person2 = person1;

  person2->setName("Karan");

  cout << person1->getName() << endl;
  cout << person2->getName() << endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Karan  
Karan
Run Code Online (Sandbox Code Playgroud)

创建没有 new 关键字的对象:

#include <iostream>
#include <string>

using namespace std;

class Person {
  private: …
Run Code Online (Sandbox Code Playgroud)

c++ class copy-constructor dynamic-memory-allocation c++17

3
推荐指数
1
解决办法
110
查看次数