开发者

C++: How to access a class function inside another class?

I am learning how to work with std::vector and want to access its values and functions. I have a vector object inside another object called spectrum. Now when I try to determine the capacity of the vector using .capacity it works fine if I just declare the vector. But when I declare the vector inside another object, I get syntax errors.

The error:

test.c++:36: error: base operand of ‘->’ has non-pointer type ‘Spectrum’

As mentioned already below, -> should be a dot.

What I want is to determine the capacity of the container, and even though it now compiles it gives result 0 instead of the 8 I would expect.

The code:

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

/*  spectrum    */
class Spectrum{
    public:
        float oct;
        vector<float> band;

        float total(){
            int k;
            float lpow;
            // logarithmic summation
            for(k = 0; k < oct; k++){
                lpow = lpow + pow(10, band[k]);
            }
            return(10*log10(lpow));
        }

        Spectrum(int max_oct = 3){
            oct = max_oct;
            cout << "max oct = " << max_oct << endl;
            vector<float> band(max_oct); //create vector/array with max_oct bands
            cout << (int)band.capacity() << endl;
        }

};

int main()
{
    //does not work in a class
    Spectrum input(8);
    cout << (int)input->band.capacity() << endl;

    //does work 开发者_StackOverflow社区outside of a class
    vector<float> band(8);
    cout << (int)band.capacity() << endl;
}


The line vector<float> band(max_oct); doesn't do what you think it does.

It defines an automatic variable called band in the scope of the Spectrum constructor. It doesn't touch the member variable also called band: in fact it "hides" it, so that any later references to band in the constructor refer to the automatic variable, not the member variable (which you could access with this->band).

What you want is:

Spectrum(int max_oct = 3) : oct(max_oct), band(max_oct) {
}

or (less good, because it constructs an empty vector and then resizes it, rather than constructing it the right size in the first place):

Spectrum(int max_oct = 3) {
    oct = max_oct;
    band.resize(max_oct);
}

By the way, I think you might be confusing the size and the capacity of vectors (not sure though from what you say). The single-arg constructor of vector creates a vector with the specified size. So if you don't already, you should expect the capacity to be 8 or more, rather than 8.

[Edit: in answer to your next question, you need to initialize lpow in total(): float lpow = 0;]


It doesn't work because you're trying to use -> on input even though input is not a pointer (or an object with a -> method). Just use input.band.capacity and it will be fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜