简体   繁体   中英

C++ calling another class constructor

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

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()
{
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM