访问C++中另一个类的方法
声明如下:
class a{
public:
void print_fib(int x){
printf("%d\n",b::getfib(x));
};
};
class b{
public:
void init(); //calculate the Fibonacci numbers, save them in `fib[]`
int getfib(int x);
private:
int fib[10];
};
class c{
private:
a ca;
b cb;
};
如何从 ca.print_fib()
访问 cb.getfib()
?
Here's the declaration:
class a{
public:
void print_fib(int x){
printf("%d\n",b::getfib(x));
};
};
class b{
public:
void init(); //calculate the Fibonacci numbers, save them in `fib[]`
int getfib(int x);
private:
int fib[10];
};
class c{
private:
a ca;
b cb;
};
How can I access cb.getfib()
from ca.print_fib()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
重新排序,否则前向声明
更好的设计决策可能是在
c::foo()
中执行b::bb()
并将结果传递给a::aa()
..那么它们可以是独立的...Re-order, else forward declare
A better design decision may be to execute
b::bb()
inc::foo()
and pass the result toa::aa()
.. then they can be independent...如果将
this
传递给 ca 和 cb,则可以使用它分别访问 cb 和 ca。If you pass
this
to ca and cb, you can use it to access cb and ca respectively.如果所有三个类都在同一个文件中,那么您的代码应该可以正常工作。
但是,如果您有单独的头文件,请将这些头文件包含到包含
class C
的文件中。比起我的回答,更喜欢埃德·希尔的评论。
if all three classes are in same file, your code should work fine.
however, if you have separate header files, include these header files into file that contains
class C
.Prefer Ed Heal's comment over my answer.
我现在看到的代码中的主要问题是从
a::print_fib
调用b::getfib(x)
,这不是正确的方法拨打此电话。b 中的函数不是静态的,除非“缓存”也设为静态,否则不可能是静态的。因此,要调用它,您需要一个 b 的实例(在 c 中有)。您可以将其传递到 a 中的函数中,但实际上在这种情况下,我不明白为什么您需要 b 的多个实例。
另请注意,从您的代码中,b 尚未在 a 的标头中声明。必须重新排列您的代码以确保正确处理依赖关系。
The main issue I see in the code as I see it now is the call to
b::getfib(x)
froma::print_fib
which is not the correct way to make this call.The function in b is not static, and cannot be unless the "cache" is also made static. Therefore to call it you need an instance of b (which you have in c). You could pass that into your function in a, but really in this case I do not see why you would need multiple instances of b.
Note also that from your code, b has not been declared yet in the header of a. Your code must be rearranged to ensure dependencies are correctly handled.