C++ calling another class constructor

2019-09-15 03:08发布

问题:

I am starting to learn about C++ classes and I have a problem. I read about constructors and initialization lists, but I still can't manage to solve my problem.

Code in 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:

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);

回答1:

why would class Line inherit from class 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; _p2 = B;}

ps not messing with business logic and access patterns

pps if you want to call base constructor from derived class ie:

class Base {}
class Derived: public Base 
{
      Derived() : Base() {}
}

or

Derived::Derived() : Base()
{
}