在我的班上,我有两个矢量对象:
std::vector<std::string> vecteur_noms_A_;
std::vector<std::string> vecteur_noms_B_;
我还有以下功能:
std::vector<std::string> & get_vecteur_noms_A_() {
return vecteur_noms_A_;
}
但我对B
没有相同的一个!
当我实例化我的类时,在我的类构造函数中执行以下指令;我可以看到(通过调试或何时抛出错误):
vecteur_noms_A_.push_back("some value"); // is ok
vecteur_noms_B_.push_back("some other value"); // is not ok <- throws an error.
调试让我看到vecteur_noms_A_
存在一个对象(或实例?)(空向量),但vecteur_noms_B_
不存在。
目前尚不清楚为什么我会观察到我没想到的那种情绪,如果我得到解释,我会很高兴。
我定义函数的事实是否强制编译器实例化对象?
这是一个例子:
#include <iostream>
#include <vector>
using namespace std;
class GP
{
public:
//Constructeur
GP(std::vector<std::string> list_names_A, std::vector<std::string> list_names_B
);
//Fonctions
void construction_vecteur_A_B_(std::vector<std::string> list_names_A, std::vector<std::string> list_names_B);
std::vector<std::string>& get_vecteur_noms_A() {
return vecteur_noms_A_;
}
std::vector<std::string> vecteur_noms_A_;
std::vector<std::string> vecteur_noms_B_;
};
GP::GP(std::vector<std::string> list_names_a, std::vector<std::string> list_names_b) {
construction_vecteur_A_B_(list_names_a, list_names_b);
}
void GP::construction_vecteur_A_B_(std::vector<std::string> list_names_a, std::vector<std::string> list_names_b)
{
for (int i = 0; i < list_names_a.size(); i++) {
vecteur_noms_A_.push_back(list_names_a[i]);
}
for (int i = 0; i < list_names_b.size(); i++) {
vecteur_noms_B_.push_back(list_names_b[i]);
}
}
int main()
{
std::vector<std::string> list_names_A = std::vector<std::string>();
std::vector<std::string> list_names_B = std::vector<std::string>();
list_names_A.push_back("A");
list_names_B.push_back("B");
GP(list_names_A, list_names_B);
return 0;
}
由于这里写的程序似乎没有错误,我想了解原因:
vecteur_noms_A_
和
vecteur_noms_B_
在执行时存在,以便我可以做回击。为什么没有必要在构造函数中将它应用于它们:
vecteur_noms_A_ = std::vector<std::string>();
vecteur_noms_B_ = std::vector<std::string>();
谢谢你的帮助。
关于你的上一个问题。在构造函数的主体执行之前,当使用类std::vector<std::string>()
时,没有必要将值(例如vecteur_noms_A_
)赋值给成员向量,vecteur_noms_B_
,GP
,因为它们是默认构造的。
因此请注意,如果您要在GP
的构造函数的主体中执行以下操作:
vecteur_noms_A_ = std::vector<std::string>();
vecteur_noms_B_ = std::vector<std::string>();
它等同于以下操作:
vecteur_noms_A_.operator=(std::vector<std::string>());
vecteur_noms_B_.operator=(std::vector<std::string>());
也就是说,您正在为已经默认构造的空向量分配一个空向量(使用复制赋值运算符),这是多余的。