d****i 发帖数: 4809 | 1 怎么在一个函数中调用某个类的数组?比如下面:
class A
{
public:
DoSomething() {...}
};
int main()
{
A a[10];
foo(a);
}
void foo(A *a)
{
int i;
for(i=0;i<10;i++)
a[i].DoSomething();
}
编译会通不过,怎么改才能实现在foo()中的循环呢? |
S**I 发帖数: 15689 | 2 这跟数组有什么关系?foo在main之前没有declare,当然编译通不过了。
【在 d****i 的大作中提到】 : 怎么在一个函数中调用某个类的数组?比如下面: : class A : { : public: : DoSomething() {...} : }; : int main() : { : A a[10]; : foo(a);
|
d****i 发帖数: 4809 | 3 写的时候忘了,foo()已经declare过了,还是不行,是不是foo()中的a[i]不能象int,
char等基本类型那样用pointer arithmetic来derefence?
【在 S**I 的大作中提到】 : 这跟数组有什么关系?foo在main之前没有declare,当然编译通不过了。
|
S**I 发帖数: 15689 | 4 你用的什么编译器?GCC没问题。
【在 d****i 的大作中提到】 : 写的时候忘了,foo()已经declare过了,还是不行,是不是foo()中的a[i]不能象int, : char等基本类型那样用pointer arithmetic来derefence?
|
z****e 发帖数: 2024 | 5 run the following!
i didn't see any problem.
#include
using std::cout;
using std::endl;
class A{
static int cnt;
int id;
public:
A():id(++cnt){}
void DoSomething() {cout<
};
int A::cnt=0;
void foo(A *a)
{
int i;
for(i=0;i<10;i++)
a[i].DoSomething();
}
int main()
{
A a[10];
foo(a);
} |
z****e 发帖数: 2024 | 6 you may need to add a return value for your member function dosomething, in
case you missed. |
e**u 发帖数: 409 | 7 报啥错?
【在 d****i 的大作中提到】 : 写的时候忘了,foo()已经declare过了,还是不行,是不是foo()中的a[i]不能象int, : char等基本类型那样用pointer arithmetic来derefence?
|
R****a 发帖数: 199 | 8 I think the major part is no problem. The following is my code and it works
by g++.
<<>
#include
class A
{
public:
void DoSomething() {printf("Inside! \n");}
};
void foo(A *a)
{
int i;
for(i=0;i<10;i++)
a[i].DoSomething();
}
int main()
{
A a[10];
foo(a);
}
build by command:
g++ try1.cc -o try1.out
run try1.out
<>
# ./try1.out
Inside!
Inside!
Inside!
Inside!
Inside!
Inside!
Inside!
Inside!
Inside!
Inside!
Do you have the compile error? You m
【在 d****i 的大作中提到】 : 怎么在一个函数中调用某个类的数组?比如下面: : class A : { : public: : DoSomething() {...} : }; : int main() : { : A a[10]; : foo(a);
|
d****i 发帖数: 4809 | 9 Thanks, I tried again and it works. No error at all.
works
【在 R****a 的大作中提到】 : I think the major part is no problem. The following is my code and it works : by g++. : <<> : #include : class A : { : public: : void DoSomething() {printf("Inside! \n");} : }; : void foo(A *a)
|
r********t 发帖数: 395 | 10
用向量的引用作为函数参数,不要用数组
【在 d****i 的大作中提到】 : 怎么在一个函数中调用某个类的数组?比如下面: : class A : { : public: : DoSomething() {...} : }; : int main() : { : A a[10]; : foo(a);
|
d****i 发帖数: 4809 | |
z****e 发帖数: 2024 | |
d****i 发帖数: 4809 | |
d****i 发帖数: 4809 | 14 An other question is: What is dynamic memory allocation is not allowed? Then
using STL such as vector will not be available. So is there a solution in
this case if class A involves with polymorphism but no STL is allowed to be
used?
【在 z****e 的大作中提到】 : probably void foo(vector &) : or : void foo(vector > smp); : arrays are very bad with polymorphism. : array arithmetic usually doesn't work when virtual call is involved.
|