[英]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.关于我改变了什么的一些笔记。
typedef
to create a new type.typedef
来创建新类型。 In C++ both class
and struct
define new types.class
和struct
定义了新类型。myVec
from dvec
, it contains the vectror myvec
, so there is no need to add a new one.dvec
派生新类型myVec
时,它包含向量myvec
,因此无需添加新类型。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.