首页 > 解决方案 > 运行时在构造函数中初始化向量类成员——C++

问题描述

我对 C++ 很陌生。

我遇到了一个问题,我的类构造函数似乎无法初始化向量类成员。构造函数需要读取文件,收集一些数据,然后在运行时调整向量的大小。

我创建了一个更简单的示例来关注这个问题。

这是头文件(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

这是源文件:

// 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;
}

我希望打印五个 0,但实际上什么也没发生。我已经考虑了一段时间,还没有找到解决方案。关于这里发生了什么的任何想法?

标签: c++vectorinitializationclass-members

解决方案


看起来问题出在这一行

cout << x + " ";

您不应该添加x空格。

它应该是cout << x << " ";


推荐阅读