我有一个下面的类foo
class foo
{
int *arr; // arr holds numbers
int sz; // size of array
public:
// Suppose I have made default and 1 parameter c'tor
foo(const foo &f)
{
sz = f.sz;
arr = new int[sz];
for(int i=0;i<sz;i++)
arr[i]=f.arr[i];
}
};
int main()
{
foo x(5); //5 is size of array
const foo y = x; //doesn't work as I haven't initialized in member-initialization list, but how to write for loop in member initialization list ?
} 那么如何在成员初始化列表中编写for循环呢?
发布于 2012-10-18 16:01:10
在本例中,您可以只使用std::vector不管怎么说。
通常,我会创建一个私有的静态方法来执行分配和复制。则可以使用初始化列表:
static int* CloneInts(const foo& f) {
int* ints = new ...
...copy them from @a f.arr...
return ints;
}然后,您的init-list将如下所示:
foo(const foo& f) : arr(CloneInts(f)), sz(f.sz) {发布于 2012-10-18 16:01:44
你有没有尝试过直接用复制构造函数来构造它?
const foo y(x);
发布于 2012-10-18 16:28:46
你应该澄清你的问题,因为问题中的那个实际上并不存在。
const foo y = x;行将与复制构造函数一起编译和工作。构造中的const对象在构造函数完成之前不是“const”,所以即使构造的对象是const,构造函数体也可以修改该对象。
还要注意的是,示例中的循环甚至没有修改任何不变的东西--因为数组是动态分配的,所以即使对象本身不是可以修改的,这些数组元素也是可以修改的。例如,在ctor完成之后,arr指针是不可修改的,但是arr[0]仍然是可修改的。
尝试下面的方法,看看这两个点的效果:
#include <stdio.h>
#include <algorithm>
class foo
{
int *arr; // arr holds numbers
int sz; // size of array
public:
foo() : arr(0), sz(0) { puts("default ctor");}
foo(int x) : arr(0), sz(x) {
puts( "int ctor");
arr = new int[sz];
for(int i=0;i<sz;i++)
arr[i]=0;
}
foo(const foo &f)
{
puts("copy ctor");
sz = f.sz;
arr = new int[sz];
for(int i=0;i<sz;i++)
arr[i]=f.arr[i];
}
~foo() {
delete [] arr;
}
foo& operator=(const foo& rhs) {
if (this != &rhs) {
foo tmp(rhs);
std::swap( arr, tmp.arr);
std::swap( sz, tmp.sz);
}
return *this;
}
void update() const {
for(int i = 0; i < sz; i++) {
arr[i] = arr[i] + 1;
}
}
void dump() const {
for(int i = 0; i < sz; i++) {
printf("%d ", arr[i]);
}
puts("");
}
};
int main()
{
foo x(5); //5 is size of array
const foo y = x;
y.dump();
y.update(); // can still modify the int array, even though `y` is const
y.dump();
} 我认为您可能会混淆构造const对象和构造具有const成员的对象,因为这些成员必须在初始化列表中初始化。
https://stackoverflow.com/questions/12949773
复制相似问题