简体   繁体   English

矢量大小不正确 - 我们如何在结构内初始化矢量

[英]Vector size is not correct - how can we initialize a vector inside a structure

I have below sample code:我有以下示例代码:

#include <iostream>
#include <vector>

typedef struct defs
{
    std::vector<int> myvec;
} dvec;

typedef struct devdef: public dvec
{
    dvec dvec1;
    devdef()
    {
          dvec1.myvec.push_back(10);
    }
}myVec;

class A
{
public:
    A():v1()
    {
         std::cout << "my vec size is " << v1.myvec.size() << std::endl;
    }
private:
    myVec v1;
};

int main()
{
     A a1;
}

Compile and execute:编译并执行:

$ c++ -std=c++11 try58.cpp

$ ./a.exe
my vec size is 0

I was expecting the size of vector to be 1 - why the same is 0?我期望向量的大小为 1 - 为什么相同的为 0?

You have dvecs as both a parent to myVec as well as a member of myVec .你有dvecs既作为家长myVec以及成员myVec In your constructor you push a value to dvec1.myvec , but in A you read v1.myvec aka the member of the parent.在您的构造函数中,您将一个值推送到dvec1.myvec ,但在A您读取v1.myvec又名父级成员。 You simply have two instances of dvecs in your structure and you're using different ones in your functions.您的结构中只有两个dvecs实例,并且您在函数中使用了不同的实例。

This version, I think, does what you wanted.这个版本,我认为,做你想要的。

#include <iostream>
#include <vector>

struct dvec
{
    std::vector<int> myvec;
}

struct myVec : public dvec
{
    myVec()
    {
          myvec.push_back(10);
    }
}

class A
{
public:
    A():v1()
    {
         std::cout << "my vec size is " << v1.myvec.size() << std::endl;
    }
private:
    myVec v1;
};

int main()
{
     A a1;
}

Some notes about what I've changed.关于我改变了什么的一些笔记。

  1. There's no need to use a typedef to create a new type.无需使用typedef来创建新类型。 In C++ both class and struct define new types.在 C++ 中, classstruct定义了新类型。
  2. When deriving the new type myVec from dvec , it contains the vectror myvec , so there is no need to add a new one.dvec派生新类型myVec时,它包含向量myvec ,因此无需添加新类型。
  3. In the constructor for the derived type myVec , we can access the myvec member of the base type directly, since it is a member of this object.在派生类型myVec的构造函数中,我们可以直接访问基类型的myvec成员,因为它是此对象的成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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