简体   繁体   中英

Initializing a vector class member in the constructor during run time — C++

I'm pretty new to C++.

I'm having an issue where my class constructor seemingly can't initialize a vector class member. The constructor would need to read a file, collect some data and then resize the vector during run time .

I created a simpler example to focus on the issue.

Here's the header file ( test.h ):

// File Guards
#ifndef __TEST_H
#define __TEST_H

// Including necessary libraries
#include <vector>

// Use the standard namespace!
using namespace std;

// Define a class
class myClass
{
    // Public members
    public:

        // vector of integers 
        vector<int> vec;

        // Declare the constructor to expect a definition
        myClass();
};

// Ends the File Guard
#endif

And here's the source file:

// Including the necessary headers
#include <iostream>
#include "test.h"

// Defining the constructor
myClass::myClass()
{
    // Loop control variable
    int i;

    // For loop to iterate 5 times
    for (i = 0; i < 5; i++)
    {
        // Populating the vector with 0s
        vec.push_back(0);
    }
}

// Main function to call the constructor
int main()
{
    // Create a "myClass" object
    myClass myObject;

    // iterating through the vector class member
    for (int x : myObject.vec)
    {
        // Outputting the elements
        cout << x + " ";
    }

    // Return statement for main function
    return 0;
}

I'd expect five 0's to be printed, but instead, nothing happens. I've thought about this for awhile and haven't found a resolution yet. Any ideas as to what's happening here?

Looks like the problem is in this line

cout << x + " ";

You should not add x with a space.

It should be cout << x << " ";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM