C ++调用另一个类的构造函数 [英] C++ calling another class constructor

查看:107
本文介绍了C ++调用另一个类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习C ++类,但遇到了问题。我了解了有关构造函数和初始化列表的信息,但仍然无法解决问题。

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.

foo.h中的代码:

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

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


推荐答案

为什么Line类从Point类继承?
解决方案:
1-不要继承Point
2-向Line类添加两个属性:Point _p1,_p2,然后从构造函数Line :: Line(Point A,点B){_p1 = A; _p2 = 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不干扰业务逻辑和访问模式

ps not messing with business logic and access patterns

pps派生类的基本构造函数,即:

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

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

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

这篇关于C ++调用另一个类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆