class A {
private:
char a;
char sub_f(char *);
public:
A();
char f(char* ) {some actions using sub_f(char*);}
};
class B {
private:
char b;
public:
B();
void execute() { b = f("some text");} //PROBLEM IS HERE
}
smb可以解释一下我如何从f(char *)
调用{A}成员的void B::execute()
函数?我现在无法编译它。如果我使f(char*)
成为A类的朋友功能,则会出现另一个问题:
friend f(char*)
对私人函数sub_f(char*)
一无所知。
我是C ++的初学者,我会非常感谢您提供完整的解答和解释。
答案 0 :(得分:0)
如果您有公共会员功能,例如
class A {
public:
char f(char* );// {some actions using sub_f(char*);}
};
你可以在实例上调用它
A a;
char just_one_char = a.f("Whatever");
同样适用于所有人 - 要调用此成员函数,您需要一个实例。
一种方法是让您的班级B
拥有A
类型的成员变量:
class B {
private:
char b;
a a;
public:
B();
void execute() { b = a.f("some text");} //PROBLEM Solved
};
如果f
不需要来自班级A
的任何实例数据,那么它可能是静态的,也可能是免费的。
也许B和A之间没有像这样的一对一关系。 也许执行可以在需要时制作A:
class B {
private:
char b;
public:
B();
void execute() {
A a;//just needed for this function call, rather than lifetime of B
b = a.f("some text"); //PROBLEM is solved a different way
}
};