[英]C++ class initialization with vector
I have inherited some code that I am looking at extending, but I have come across a class\\constructor that I have not seen before. 我继承了一些我正在寻求扩展的代码,但是我遇到了一个我之前从未见过的类\\构造函数。 Shown below in the code snippet
如下所示在代码段中
class A {
public:
A() {};
~A() {};
//protected:
int value_;
class B: public std::vector<A> {
public:
B(int size = 0) :
std::vector<A>(size)
{}
So from what I gather class B
is a vector of class A
which can be accessed using the *this
syntax because there is no variable name. 所以我收集的是
class B
class A
它是class A
class B
的向量,可以使用*this
语法访问,因为没有变量名。 I would like to initiate class A
in the constructor, but I am unsure how to do this with in this context. 我想在构造函数中启动
class A
,但我不确定如何在此上下文中执行此操作。 I have looked at this but they have declared the vector as an object where in this case it is the class. 我看过这个但是他们已经将向量声明为一个对象,在这种情况下它是类。
This seems slightly different from normal inheritance where I have inherited many instances of a single class, compared to the usual one to one in most text books. 这似乎与正常继承略有不同,在正常继承中,我继承了单个类的许多实例,而在大多数教科书中通常都是一对一的。 What I was trying to do, was propagate a value to intialise
class A
through both class B
and class A
constructor. 我试图做的是通过
class B
和class A
构造函数将值传播到初始化class A
Something like below is what I tried but doesn't compile. 像下面这样的东西是我尝试但不编译的东西。
#include <iostream>
#include <vector>
using namespace std;
class A {
public:
A(int int_value) :
value_(int_value)
{};
~A() {};
//protected:
int value_;
};
class B: public vector<A> {
public:
B(int size = 0, int a_value) :
vector<A>(size, A(a_value))
{};
vector<int> new_value_;
void do_something() {
for (auto& element : *this)
new_value_.push_back(element.value_);
}
};
int main() {
cout << fixed;
cout << "!!!Begin!!!" << endl;
B b(20,23);
cout << b.size() << endl;
b.do_something();
for(auto& element : b.new_value_)
cout << element << endl;
cout << "finished" << endl;
system("PAUSE");
return 0;
}
I guess a follow up question is, is this a good implementation of what this code is trying to achieve 我想一个后续问题是,这是一个很好的实现这个代码试图实现的目标
B(int size = 0, int a_value) ...
is incorrect. 是不正确的。 You may not have an argument with a default value followed by an argument that does not have a default value.
您可能没有带有默认值的参数,后跟没有默认值的参数。
Possible resolutions: 可能的决议:
Provide default values for both arguments. 为两个参数提供默认值。
B(int size = 0, int a_value = 0) ...
Provide default value only for the second argument. 仅为第二个参数提供默认值。
B(int size, int a_value = 0) ...
Change so that neither has a default value. 更改,以便它们都没有默认值。
B(int size, int a_value) ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.