0

所以,我有一个相当具体的问题,我一生都无法在互联网上的任何地方找到参考。

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

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

    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

我在互联网上进行了广泛的搜索,也许我的搜索词有问题,但我使用了我能想到的每一个词组合来试图找到答案。/叹

注意,这是家庭作业,但您的解释/帮助将不胜感激!

4

1 回答 1

0

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

您需要在您的类 licenseCount(等等)中将 y_array 声明为 std::string,而不是在 calc_vol 中。calc_vol 中的错误声明将掩盖 y_array 的正确类内成员声明。稍后与 y_array[i] 的使用将保持不变,除了引用 this->y_array (“this->”将是隐含的)。

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

于 2012-09-06T17:50:41.077 回答