【发布时间】:2016-08-18 15:19:02
【问题描述】:
我正在寻找一些关于如何组织我的 C++ 代码的建议。
我有一个 int 数组 side,我希望它是静态的,因为它的值在调用之间保持不变。这是因为我的函数 foo() 将递归地修改数组边,所以我不希望复制边。此外,side 的大小只能在编译时根据传递给函数 bar() 的向量的大小来确定。
我想到了下面的结构来布局这样的问题。
我保留了一个全局 int 指针 side,然后我可以使用它来指向我的 int 数组的地址,然后使用 foo 中的指针 *side 进行修改。
请你给我关于这段代码的布局和组织的建议吗?我对 C++ 还很陌生,所以如果对以下结构有任何建议,我将不胜感激。
#include <iostream>
#include <vector>
using namespace std;
int *side;
class A {
public:
int foo(bool);
int bar(vector<int>);
void set_n(int n){ class_n = n;};
private:
int class_n;
};
int A::foo(bool fl)
{
int n = class_n;
for(int i = 0; i < n; i++) {
// modify side[] and then recursively call foo
}
return 0;
}
int A::bar(vector<int> t)
{
int size = t.size();
set_n(size);
int a = foo(true);
int *side_local = new int[size];
for(int i = 0; i < size; i++) {
side_local[i] = 0;
}
side = side_local;
return 0;
}
int main()
{
A a;
vector<int> t = {1, 2, 3};
a.bar(t);
return 0;
}
【问题讨论】:
-
为什么包含
<vector>,但在这里没有使用:int *side_local = new int[size];?为什么不简单地std::vector<int> side_local(size);?或者只是简单地side.resize(size);而不执行任何代码? -
这取决于上下文,你什么都不给。数组应该代表什么?它是否以某种方式与 A 相关联?它应该归 A 所有吗?为什么不使用向量?您不会通过传递引用或指针来复制...