gpt4 book ai didi

c++ - 如何从另一个类参数访问类构造函数参数

转载 作者:行者123 更新时间:2023-12-01 15:10:47 24 4
gpt4 key购买 nike

与C++构造函数争论不休

因此,我只是来自TS / JS / Py,并试图了解C++概念。但是我正在努力使用类的构造函数的参数来声明参数的默认值。这是我要运行的代码:

double Phythagorean_Hypotenuse (int& a, int& b ) {
return sqrt((a * a) + (b * b));
};

class Triangle {
public:
int a;
int b;
double c;
Triangle(int a_param, int b_param, double c_param = Phythagorean_Hypotenuse(a_param, b_param)) {
a = a_param;
b = b_param;
c = c_param;
}
};

和主要功能的内部
Triangle mytri_1(10, 20);
std::cout << mytri_1.a << std:endl;

但是,当我尝试运行此代码时,IDE向我抛出了一些错误,例如

[Error] 'a_param' was not declared in this scope

要么

[Error] call to 'Triangle::Triangle(int, int, double)' uses the default argument for parameter 3, which is not yet defined

因此,请解决这一问题的人可以回答这个问题吗?

谢谢。

最佳答案

有一些问题会阻止您的代码编译,即:

  • 构造函数没有返回类型。
  • double c_param = Phythagorean_Hypotenuse(a_param, b_param)对参数无效,因此无法识别a_param, b_param

  • 推荐更改:

    由于假设计算的结果很可能是十进制值,因此 c应该是 double

    您可以执行以下操作:

    Running sample
    #include <iostream>
    #include <cmath>

    double Phythagorean_Hypotenuse (int& a, int& b ) {
    return sqrt((a * a) + (b * b));
    };

    class Triangle {
    public:
    int a;
    int b;
    double c; //should be double

    //initializer list is a good practice for member initialization
    Triangle(int a_param, int b_param)
    : a(a_param), b(b_param), c(Phythagorean_Hypotenuse(a, b)) {}
    };

    int main(){

    Triangle mytri_1(10, 20);
    std::cout << mytri_1.a << std::endl;
    std::cout << mytri_1.b << std::endl;
    std::cout << mytri_1.c << std::endl;
    }


    输出:

    10
    20
    22.3607

    关于c++ - 如何从另一个类参数访问类构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60940095/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com