【问题标题】:How do I create a vector that holds objects?如何创建包含对象的向量?
【发布时间】:2020-02-10 01:14:17
【问题描述】:

我正在尝试创建一个可以容纳多个现有对象的向量,但我遇到了麻烦。在 Visual Studio 中,它说“此声明没有存储类或类型说明符”。

代码如下:

#include <iostream>
#include <vector>
#include <string>

struct test {
    int id;

    test(int i) {
        id = i;
    }
};

test obj1(1);
test obj2(2);
test obj3(3);

std::vector<test> egg;

egg.push_back(obj1);
egg.push_back(obj2);
egg.push_back(obj3);

int main() {}

【问题讨论】:

    标签: c++ object vector


    【解决方案1】:

    我认为该程序的问题在于您的所有代码都在 main 方法之外,因此编译器不知道如何处理它。

    【讨论】:

      【解决方案2】:

      您不能在文件/命名空间范围中编写表达式语句,例如egg.push_back(obj1);,而声明/定义例如@987654322 @。 表达式语句只能在块范围中使用,即在函数体内。例如

      int main() {
          egg.push_back(obj1);
          egg.push_back(obj2);
          egg.push_back(obj3);
      }
      

      同时避免使用全局变量并将所有变量声明/定义也放在本地范围内:

      int main() {
          test obj1(1);
          test obj2(2);
          test obj3(3);
      
          std::vector<test> egg;
      
          egg.push_back(obj1);
          egg.push_back(obj2);
          egg.push_back(obj3);
      }
      

      另外,与问题无关,使用构造函数的成员初始化列表初始化成员,而不是分配给构造函数体:

      test(int i) : id(i) {
      }
      

      【讨论】:

        【解决方案3】:

        正如 zach 所说,您的 main 方法之外还有代码。 std::vector&lt;test&gt; egg; 允许在 int main 之外使用,但像 egg.push_back(obj1); 这样的函数不允许

        修改代码:

        #include <iostream>
        #include <vector>
        #include <string>
        
        struct test {
            int id;
        
            test(int i) {
                id = i;
            }
        };
        
        test obj1(1);
        test obj2(2);
        test obj3(3);
        
        std::vector<test> egg;
        
        int main() {
            egg.push_back(obj1); //moved to main
            egg.push_back(obj2); //moved to main
            egg.push_back(obj3); //moved to main
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-30
          • 1970-01-01
          相关资源
          最近更新 更多