没有匹配函数调用构造函数问题(关于类基础语法的问题)

编程入门 行业动态 更新时间:2024-10-22 11:38:32
本文介绍了没有匹配函数调用构造函数问题(关于类基础语法的问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

(我是这个平台的新手,如果我问错了,抱歉.)

(I'm new to use this platform, sorry if I ask the question incorrectly .)

我正在尝试将点的协调传递给段类,为了计算段的长度,但代码块返回错误消息:谁能告诉我如何解决这个问题

I'm trying to pass the coordination of point to the segment class, in order to compute length of the segment, but codeblocks return error message: could someone tell me how to solve this problem

#include <iostream>
#include <cmath>
using namespace std;
class Point
{
public:
    Point(float in1, float in2):x(in1),y(in2){};
    float x, y;
};

class Segment
{
public:
    Segment(Point in1, Point in2){
        this->a.x = in1.x;
        this->a.y = in1.y;
        this->b.x = in2.x;
        this->b.y = in2.y;
    };
    float length() //return the length of segment
    {
        float delta_x = a.x - b.x, delta_y = a.y - b.y;
        return sqrt( delta_x * delta_x + delta_y * delta_y);
    };
private:
    Point a, b;

};

int main(){
    Point a(12,5),b(6,6);
    Segment seg1(a, b);
    cout << seg1.length();

}

推荐答案

必须在进入构造函数体之前构造所有类成员.

All class members must be constructed before entering the body of the constructor.

Segment(Point in1, Point in2)
{ // The constructors for a and b WILL be called before this brace
    this->a.x = in1.x;
    this->a.y = in1.y;
    this->b.x = in2.x;
    this->b.y = in2.y;
};

如果成员有一个默认构造函数,一个可以不带参数调用的构造函数,这很容易做到.Point 没有这样的构造函数.为了构建一个点,您必须提供 in1in2 并且只能通过 Member Initializer List 或通过提供 默认成员初始化器.第二个选项在这里不合适,因为不需要默认值.

This is easy to do if the members have a default constructor, a constructor that can be called with no arguments. Point has no such constructor. In order to construct a point you must provide in1 and in2 and those can only be provided with a Member Initializer List or by providing Default Member Initializers. The second option is not appropriate here because default values are not desired.

但是,在这种情况下,您可以利用 Point 自动生成的复制构造函数来简化您的工作.

However in this case you can take advantage of Point's automatically-generated copy constructor to make your job a bit easier.

Segment(Point in1, Point in2){
    this->a.x = in1.x;
    this->a.y = in1.y;
    this->b.x = in2.x;
    this->b.y = in2.y;
};

变成

Segment(Point in1, Point in2):
   a(in1), b(in2) 
{
    //does nothing
};

这篇关于没有匹配函数调用构造函数问题(关于类基础语法的问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 13:07:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410158.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   语法   基础

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!