[英]C++ calling another class constructor
I am starting to learn about C++ classes and I have a problem. 我开始学习C ++类,但遇到了问题。 I read about constructors and initialization lists, but I still can't manage to solve my problem. 我阅读了有关构造函数和初始化列表的信息,但仍然无法解决问题。
Code in foo.h: foo.h中的代码:
class point{
public:
double x,y;
point(double x1, double y1);
};
class line: public point{
public:
double A,B,C;
double distance(point K);
line(point M, point N);
};
And in foo.cpp: 在foo.cpp中:
point::point(double x1, double y1){
x=x1;
y=y1;
}
line::line(point M, point N){
if(M.x!=N.x){
A=-(M.y-N.y)/(M.x-N.x);
B=1;
C=-(M.y-A*M.x);
}
else{
A=1;
B=0;
C=-M.x;
}
}
Of course it does not work, because I don't know how to call point constructor in line constructor. 当然这是行不通的,因为我不知道如何在行构造器中调用点构造器。 How can i do this? 我怎样才能做到这一点? I would like to do sth like that: 我想做某事:
point A(5,3),B(3,4);
line Yab(A,B);
why would class Line inherit from class Point? 为什么Line类将从Point类继承? solution: 1 - don't inherit from Point 2 - add two properties to Line class: Point _p1, _p2, and then initialize it from constructor Line::Line(Point A, Point B) { _p1 = A; 解决方案:1-不要继承Point 2-向Line类添加两个属性:Point _p1,_p2,然后从构造函数Line :: Line(Point A,Point B)对其进行初始化。 _p2 = B;} _p2 = B;}
ps not messing with business logic and access patterns ps不搞乱业务逻辑和访问模式
pps if you want to call base constructor from derived class ie: 如果要从派生类调用基构造函数,则为pps,即:
class Base {}
class Derived: public Base
{
Derived() : Base() {}
}
or 要么
Derived::Derived() : Base()
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.