派生类无法访问私有成员(尽管构造函数是在基类中定义的)
Private member cannot be accessed by derived class (eventhough constructor is defined in the base class)
有人能告诉我我在下面的程序中做错了什么吗?:
// 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;
}
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 参数包构造函数在类模板中隐藏用户定义的转换
- 具有已删除移动和复制构造函数的类的就地构造
- 创建一个没有复制构造函数的类的 std::vector 的 std::vector
- C++构造函数和类?
- 在 C++ 中,默认情况下构造函数为类的数据成员提供的值是多少?
- 如何在其他类中使用参数化构造函数制作类的对象?
- 具有值包装器的可变参数模板构造函数的类构造函数优先级
- 如何使用私有构造函数对类进行单元测试?
- C++虚拟函数:基类函数是调用的,而不是派生的
- c++17在编译时将带有已删除复制构造函数的类添加到std::vector
- 从作为模板参数传递给构造函数的类继承,或者从它们继承
- 继承的构造函数忽略类内初始化
- 模板和隐式构造函数的类定义之外的友元声明
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 为什么具有私有构造函数的类不阻止从此类继承?如何控制哪些类可以从某个基继承?
- 具有多个非默认构造函数基的Singleton派生类
- 调用基默认构造函数模板类
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 构造所有基类不需要默认生成的构造函数