是int一个class?
请考虑下面的代码
#include"iostream"
using namespace std;
class test{
public:
int a;
test(int x)
{
cout<<"In test Constructor"<<endl;
a = x;
}
};
int main()
{
test *obj = new test(10);// Constructor get called
int *x = new int(10); // Expecting the same if "int" is a class
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不,int不是class,并且int x = new int(10);不是有效的 C++ 语法。
int* x = new int(5);
...
...
delete x;
Run Code Online (Sandbox Code Playgroud)
这只是创建一个指向 an 的指针int,并且new int(5)是初始化指针的一种方法。
而正确的做法应该是delete[] x;
不,因为您将其分配为new,而不是new[]。正确的方法是int x = 5;或者int x(5);- 除非真正必要,否则避免动态分配。
| 归档时间: |
|
| 查看次数: |
15901 次 |
| 最近记录: |