【发布时间】:2021-03-12 07:36:49
【问题描述】:
我正在重新定义以下代码的类错误。但是如果我把这个定义放在一个循环中,就没有错误。有什么区别?
using namespace std;
#include <iostream>
using namespace std;
struct MyClass
{
int x;
};
int main()
{
MyClass A;
MyClass A;
return 0;
}
我试过了,但仍然有同样的重新定义错误:
#include <iostream>
using namespace std;
struct MyClass
{
int x;
};
int main()
{
MyClass* A;
delete(A);
MyClass* A;
delete(A);
return 0;
}
但是,如果我把它放在一个循环中也没问题:
using namespace std;
struct MyClass
{
int x;
};
int main()
{
for (int i = 0; i < 5; i++) {
MyClass A;
}
return 0;
}
那么有什么区别呢?以及如何删除和重新定义具有相同名称的类。我不想找到不同的名字。我将在循环之外使用它并在向量中推回它们。
其实我想做的是:
#include <iostream>
#include <vector>
using namespace std;
struct MyClass
{
int x;
// other variables vectors etc.
};
vector <MyClass> v_A;
int main()
{
MyClass A;
// Use A's methods and give values to its variables and vectors.
v_A.push_back(A);
MyClass A2;
// Use A's DIFFERENT methods and give values to its variables and vectors.
v_A.push_back(A2);
MyClass A3;
// Use A's AGAIN DIFFERENT methods and give values to its variables and vectors.
v_A.push_back(A3);
// Goes on. I don't want to create different objects A A2 A3 ... A30. I don't want to keep them in the memory.
// I don't want to write 2 3 ... 30
// Is there a way to get rid of them from memory?
return 0;
}
更新代码以包含一个取决于 linsock 答案的解决方案:
#include <iostream>
#include <vector>
using namespace std;
struct MyClass
{
int x;
// other variables vectors etc.
};
vector <MyClass> v_A;
int main()
{
{
MyClass A;
// Use A's methods and give values to its variables and vectors.
v_A.push_back(A);
}
{
MyClass A;
// Use A's DIFFERENT methods and give values to its variables and vectors.
v_A.push_back(A);
}
{
MyClass A;
// Use A's AGAIN DIFFERENT methods and give values to its variables and vectors.
v_A.push_back(A);
}
// Goes on. I dont want to create different classes A A2 A3 ... A30. I dont want to keep them in the memory.
// I dont want to write 2 3 ... 30
// Is there a way to get rid of them from memeory?
return 0;
}
【问题讨论】:
-
您重新声明 A 两次,而只是分配新值。
MyClass * A = new MyClass();delete A;A = new MyClass(); -
delete(A);你有Python背景吗? -
@fvalasiad 这次它给出了错误:'A': redefinition;多次初始化
-
@Ayxan Haqverdili 不,我没有。
-
注意:在您包含任何
std头文件之前,using namespace std;毫无意义。您可能还想看看Why isusing namespace std;considered bad practice?
标签: c++ class redefinition