c++ - 运行时在构造函数中初始化向量类成员——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,但实际上什么也没发生。我已经考虑了一段时间,还没有找到解决方案。关于这里发生了什么的任何想法?
解决方案
看起来问题出在这一行
cout << x + " ";
您不应该添加x
空格。
它应该是cout << x << " ";
推荐阅读
- selenium-webdriver - 如何为 web 和 andorid 本机应用程序的失败截取屏幕截图
- sql - 加入具有重复值的列时避免重复
- oracle - 我们如何在 Oracle Merge 语句中使用 use parallel (10) 提示
- python - 如何在 python 中裁剪 PNG 图像?
- elasticsearch - 弹性搜索同义词错误
- git - 在推送到 Master 之前查看功能分支的特定更改
- qt - 在 Ubuntu 21.04 上安装 Qt5
- postgresql - 如何在 Debian 9 中安装 utf8 语言环境
- google-sheets - 尝试 COUNTIFS 日期 = 本周(周日至周六)?
- pandas - 尝试使用 beauifulsoup 遍历列表时,For 循环返回错误