C++中创建对象的方式
无参数的情况
- 隐式创建:
A a1; - 显式创建:
A a2 = A(); - 通过new关键字创建,返回的是指针:
A *a3 = new A();
#include <iostream>
using namespace std;
class A {
public:
int id;
};
int main() {
A a1;
a1.id = 1;
A a2 = A();
a2.id = 2;
A *a3 = new A();
a3->id = 3;
cout << "a1.id == " << a1.id << endl;
cout << "a2.id == " << a2.id << endl;
cout << "a3->id == " << a3->id << endl;
return 0;
}
有参数的情况
- 隐式创建:
A a1; - 显式创建:
A a2 = A(); - 通过new关键字创建,返回的是指针:
A *a3 = new A();
#include <iostream>
using namespace std;
class A {
public:
int id;
A();
A(int);
};
A::A() {
id = -1;
}
A::A(int id) {
this->id = id;
}
int main() {
A a1(1);
A a2 = A(2);
A *a3 = new A(3);
cout << "a1.id == " << a1.id << endl;
cout << "a2.id == " << a2.id << endl;
cout << "a3->id == " << a3->id << endl;
return 0;
}
什么时候使用new关键字
-
申请对象占内存特别大的时候 -
作为函数的返回值 #include <iostream>
using namespace std;
class A {
public:
int id;
A();
A(int);
};
A::A() {
id = -1;
}
A::A(int id) {
this->id = id;
}
A getObject1(int id) {
A a1(id);
return a1;
}
A* getObject2(int id) {
A *a2 = new A(id);
return a2;
}
int main() {
A a1 = getObject1(1);
A *a2 = getObject2(2);
cout << "a1.id == " << a1.id << endl;
cout << "a2->id == " << a2->id << endl;
return 0;
}
-
两个类互相引用 #include <iostream>
using namespace std;
class A;
class B;
class A {
public:
int id;
B *b;
A(int);
A(B*);
};
A::A(int id) {
this->id = id;
}
A::A(B *b) {
this->b = b;
}
class B {
public:
int id;
A *a;
B(int);
B(A*);
};
B::B(int id) {
this->id = id;
}
B::B(A *a) {
this->a = a;
}
int main() {
A *a = new A(1);
B *b = new B(2);
a->b = b;
b->a = a;
cout << "a->id == " << a->id <<endl;
cout << "a->b->id == " << a->b->id <<endl;
cout << "b->id == " << b->id <<endl;
cout << "b->a->id == " << b->a->id <<endl;
return 0;
}
如果不使用指针,编译无法通过 #include <iostream>
using namespace std;
class A;
class B;
class A {
public:
int id;
B b;
};
class B {
public:
int id;
A a;
};
int main() {
return 0;
}
|