【发布时间】:2019-11-16 10:14:51
【问题描述】:
我现在正在学习 C++ 中的 OOP,但遇到了一个小问题。
在基类中使用列表初始化时,如何从派生类中的基类获取私有数据?
class CPunct
{
private:
double x;
double y;
public:
CPunct(double a, double b) : x(a), y(b) {} //initialization list
};
class CDreapta :public CPunct
{
public:
friend void lineFrom2Points(CPunct& a, CPunct& b) // Function to find the line by two points
{
double expr1 = b.y - a.y; //expresion 1
double expr2 = a.x - b.x; //expresion 2
double expr3 = expr1 * (a.x) + expr2 * (a.y); //expresion 3
if (expr2 < 0)
{
std::cout << "The line passing through points a and b is: "
<< expr1 << "x " << expr2 << "y = " << expr3 << "\n";
}
else
{
std::cout << "The line passing through points a and b is: "
<< expr1 << "x + " << expr2 << "y = " << expr3 << "\n";
}
}
};
在我的代码中,我尝试将使用来自基类 CPunct 的私有数据的函数 (lineFrom2Points) 声明为友元,但它似乎不起作用。 请给我一个建议!谢谢!
【问题讨论】:
标签: c++ oop inheritance