C++ 如何在c++;

C++ 如何在c++;,c++,C++,我无法从派生类a访问类b的值name。我该怎么做 #include<iostream> #include<string> using namespace std; class a { public: void getname() { string name; //trying to access value from other child class cout << "enter your name" &l

我无法从派生类
a
访问类
b
的值
name
。我该怎么做

#include<iostream>
#include<string>
using namespace std;

class a
{

public:
    void getname()
    {
        string name; //trying to access value from other child class
        cout << "enter your name" << endl;
        getline(cin, name);
        cout << " your name is " << name << endl;
    }
};
class b: public a
{
    int age;

public:
    void old()
    {
        cout << "enter your age" << endl;
        cin >> age;
        cout << "your age is" << age << endl;
    }
    void print()
    {
        cout << " your name is " << name << endl; //cant access it
        cout << "your age is" << age << endl;
    }
};

int main()
{
    b o;
    o.getname();
    o.old();
    o.print();
    return 0;
}
#包括
#包括
使用名称空间std;
甲级
{
公众:
void getname()
{
字符串名称;//试图从其他子类访问值

cout您在getname()函数内声明了name,而不是作为类成员。函数内声明的变量具有块作用域,这意味着它们不再存在于该函数外。下面是有关作用域的详细信息。它还可以帮助您处理类作用域/类成员

试着像这样更改classa

class a {
   protected:
        string name;
    public:
        void getname() {
            cout << "enter your name" << endl;
            getline ( cin,name);
            cout << " your name is " << name << endl;
    }
};
a类{
受保护的:
字符串名;
公众:
void getname(){

请在问题中以文本形式发布代码。这使人们更容易自己测试代码。这里有点新,谢谢
name
不是实例字段。它是函数的局部变量,无法访问。如果您打算将其作为实例字段,请将其定义移到
getname
之外Action.已经这样做了实际上这是我的第一个程序,但仍然显示错误我只是注意到我的答案有一个私有成员的名称,它应该受到保护。重要的是你不要在getname()中声明名称。谢谢先生,我注意到我的错误,我真的需要检查public protected和private的用法