派生类无法访问私有成员(尽管构造函数是在基类中定义的)

Private member cannot be accessed by derived class (eventhough constructor is defined in the base class)

本文关键字:构造函数 基类 定义 访问 成员 派生      更新时间:2023-10-16

有人能告诉我我在下面的程序中做错了什么吗?:

// C++-Assignment2.cpp
#include <iostream.h>
#include <conio.h>
class fahrenheit
{
    private:
        int fah;
    public:
        fahrenheit()
        {
            fah=0;
      }
        void fget();
        void fdisp();
};
class celsius: public fahrenheit
{
    private:
        int cel;
    public:
    void calc();
        void cdisp();
};
void fahrenheit::fget()
{
    cout<<"n Enter temperature value in Fahrenheits:";
    cin>>fah;
}
void fahrenheit::fdisp()
{
    cout<<"n  Temperature in Fahrenheits: "<<fah;
}
void celsius::calc()
{
  cel=5*(fah-32)/9;
}
void celsius::cdisp()
{
    cout<<"n Temperature in Celsius:"<<cel;
}
void main()
{
    clrscr();
    celsius c1;
    c1.fget();
    c1.fdisp();
    c1.calc();
    c1.cdisp();
    getch();
}

如果之前有人问过我,我很抱歉,但我找不到用户提到他们包含构造函数的问题(就像我做的那样)。此外,我确实理解这个程序并没有那么大意义(考虑到我是如何构建这两个单元的)。还是一个初学者,所以目前还没有真正进入"完善"语义。

错误:

Compiling 2-ASSIGN.CPP:
Error 2-ASSIGN.CPP 36: 'fahrenheit::fah' is not accessible in function celsius::calc()
Error 2-ASSIGN.CPP 36: 'fahrenheit::fah' is not accessible in function celsius::calc()

在此成员函数中

void celsius::calc()
{
  cel=5*(fah-32)/9;
}

您正试图访问基类的私有数据成员fah

您可以声明它具有受保护的访问控制。例如

class fahrenheit
{
    protected:
        int fah;
    //...
};

或者,您可以定义一个公共成员函数来返回此数据成员的值。

对于我来说,这个类层次结构没有意义。:)

void celsius::calc()
{
   cel=5*(fah-32)/9; 
 }

您尝试访问专用的fah。派生类无法访问私有成员。在好的设计中,基类中会有一个公共getter方法,可以用来获取派生类中fah的值。

类似的东西

int farenhiet::get_fah()
{
    return fah;
}

然后在派生类中

void celsius::calc()
{
   cel=5*(get_fah()-32)/9; 
 }