问题描述
class A
{
public:
class B
{
public:
int changevar (int b)
{
a = b; // 5 should go in "a"
}
int get()
{
return a;
}
protected:
int a = 0; // value initialized here
};
private:
int usechangedvar(B& hello);
};
int A::usechangedvar(B& hello)
{
int final = hello.get(); // 5 should go in "final"
return final;
}
int main()
{
A::B hi;
hi.changevar(5);
A obj;
obj.usechangedvar(hi);
}
这段代码不会编译,因为它会说我正在尝试访问私有方法。 无论如何,我不确定这样做的正确方法是什么,但最终我想要的是: 在 B 类下有一个受保护的变量,它的值由称为“changevar”的公共方法更改。更改值后,我需要将该值存储在名为“usechangedvar”的私有方法内的变量“final”中。
注意:我不想将变量“a”从 protected 更改为其他内容。
编辑:我愿意接受 B 类不是嵌套类的建议。我可以把它放在外面意味着 A 和 B 不在彼此之内
编辑:
#include <stdio.h>
#include <iostream>
#include <stdint.h>
class A
{
public:
class B
{
public:
int changevar (int b) ------------- This method is called by application code(user) and whatever value user gives here should be the changed value
{
a = b; // 5 should go in "a"
}
// int get()
// {
// return a;
// }
protected:
int a = 0; // value initialized here. This Could be anything private/protected
};
class C : public class B
{
};
private:
int usechangedvar();
};
int A::usechangedvar()
{
// 5 should come here which was inputted by user.
}
int main()
{
//1) I instantiate class C by doing
A::C objC;
objC.changevar(5);
// Whole purpose is to take 5 from user and then use it eventually in "usechangedvar" method.
}
解决方法
以下是您的问题,删除了不相关的细节:
class A
{
private:
int usechangedvar(int hello) { return hello; }
};
int main()
{
A obj;
obj.usechangedvar(5); //compile error,usechangedvar is private
}
您的代码中的问题与类 B
完全无关,正如您在此处看到的 - 您不能从 A::usechangedvar()
调用 main()
,因为它是类 A
的私有方法。
如果您只需要检查您的方法 usechangedvar()
是否有效,您可以将公共方法添加到 A,例如 test()
,从中调用 usechangedvar()
并可能打印结果。然后您可以从 obj.test()
调用 main()
并查看它是否有效。如有必要,您可能希望在测试完成后删除该方法 test()
。