如何重载*op以乘以常量和单个dim数组成员

How to overload * op to multiply constant and single dim array member

本文关键字:常量 dim 组成员 数组 单个 op 何重载 重载      更新时间:2023-10-16

所以,我有一个相当具体的问题,我一生都找不到在互联网上引用的。

我想知道如何重载*运算符,这样我就可以在常数和数组的一部分之间相乘。

我的代码,至少是相关的部分,如果需要更多,我可以发布:

    licenseCount licenseCount::operator * (const licenseCount& u) const
    {
        return(this->fxdx*u.fxdx, this->y_array*u.y_array);
    }
    int licenseCount::calc_vol(double z, char *argv[])
    {
        int area;
        std::string y_array[9];
        std::ifstream y_data;
        y_data.open( argv[1] );
        if(y_data.fail())
        {
            std::cout << "Can't open file!n";
            exit(1);
        }
        else
        {
            for(int i=0; i<=9;i++)
            {
                int temp;
                y_data >> y_array[i];
                std::cout << y_array[i] << 'n';
                if(i%2 == 0)
                {
                    temp = 2 * y_array[i];
                    area += fxdx * temp;
                }
                else if(i = 0)
                {
                   area += fxdx * y_array[i];
                }
                else
                {   
                   temp = 4 * y_array[i];
                   area += fxdx * temp;
                }
                std::cout << area;
            }
        vol = area * depth;
        return vol;
    }

我的错误:

licenseCount.cpp:62: error: 'const class licenseCount' has no member named 'y_array'
licenseCount.cpp:62: error: 'const class licenseCount' has no member named 'y_array'
licenseCount.cpp: In member function `int licenseCount::calc_vol(double, char**)':
licenseCount.cpp:90: error: no match for 'operator*' in '2 * y_array[i]'
licenseCount.cpp:91: warning: converting to `int' from `double'
licenseCount.cpp:95: error: no match for 'operator*' in '((licenseCount*)this)-licenseCount::fxdx * y_array[i]'
licenseCount.cpp:98: error: no match for 'operator*' in '4 * y_array[i]'
licenseCount.cpp:99: warning: converting to `int' from `double'
licenseCount.cpp:111: error: a function-definition is not allowed here before '{' token
licenseCount.cpp:113: error: expected `}' at end of input

我在互联网上搜索了很多遍,也许我的搜索词有错误,但我使用了我能想到的每一个单词组合来试图找到答案/叹息

请注意,这是家庭作业,但我们将非常感谢您的解释/帮助!

看起来您正试图通过u.y_array表示法访问y_array,这是一个仅对calc_vol本地的变量,该表示法将引用y_array(类许可证计数的成员),该名称空间与您的代码所示的y_array声明的名称空间不同。

您需要在类licenseCount中(依此类推)将y_array声明为std::字符串,而不是在calc_vol中。calc_vol中的错误声明将屏蔽y_array的类内正确成员声明。稍后对y_array[i]的使用将保持不变,而不是引用this->y_array("this->"将是隐式的)。

在licenseCount中使用这个是多余的,因为类方法可以引用没有"this->"的实例方法。