[英]How to store a variable in a header, to use in the main cpp?
I tried asking this question, it was a bit more fuzzy on the details, but now I arrived home and I hope I can explain myself better. 我试着问这个问题,细节上有些模糊,但是现在我回到家了,希望我能更好地解释自己。
Say, I have a class, in this case, TestClass
, I declared its constructor and methods in TestClass.h
already. 说,我有一个类,在这种情况下为TestClass
,我已经在TestClass.h
声明了它的构造函数和方法。 Now, I want to create a new array of these elements, and store them somewhere, to load in to my main.cpp
, when I want to. 现在,我想创建一个由这些元素组成的新数组,并将它们存储在某个地方,以便在需要时加载到main.cpp
中。
What I tried doing, is, doing this in a new header, I called Contents Table.h
. 我尝试做的是在新的标头中执行此操作,我将其称为Contents Table.h
。 Here, I tried making an array of these TestClass
elements. 在这里,我尝试制作这些TestClass
元素的数组。 However, I don't really know, how to go about properly doing this. 但是,我真的不知道如何正确执行此操作。
Testclass.h 测试类
#pragma once
#include <string.h>
#include <iostream>
using namespace std;
class TestClass
{
private:
string name;
string description;
public:
TestClass()
{
name = "";
description = "";
}
TestClass(string name, string description)
{
this->name = name;
this->description = description;
}
~TestClass()
{
}
};
And here is the Contents Table, where I want to store my data, that I manually write in, I had two ideas about doing this, not sure which one is feasible: 这是目录表,我要在其中存储我手动写入的数据,我对此有两种想法,不确定哪一种可行:
First idea: 第一个想法:
ContentsTable.h 目录表
#include "Testclass.h"
TestClass* buildData(void)
{
TestClass* World = new TestClass[5];
World[0] = TestClass("A", "A");
//Etc, fill the rest up.
return World;
}
And in the main.cpp, I'd call this function, like 在main.cpp中,我将调用此函数,例如
#include "Contents Table.h"
//...
TestClass* DataArray = buildData();
Second idea: 第二个主意:
ContentsTable.h 目录表
#include "Testclass.h"
namespace DataArray2
{
extern TestClass* DataArray2 = new TestClass[5];
DataArray2[0] = TestClass("A", "A");
};
And I'd declare it again in the main.cpp, but the second one things, I'm trying to redeclare the DataArray2, when I try giving one if its elements value. 我会在main.cpp中再次声明它,但第二件事是,当我尝试给出其元素值时,我试图重新声明DataArray2。 (Again, I'm sure it's my fault with this, sorry, if it seems like a really banal code, I haven't been learning for long.) (再次,我敢肯定这是我的错,对不起,如果它看起来像是一本平淡的代码,我已经学习了很长时间了。)
Not sure if this meets your requirements, but I'd make buildData
look like this (C++11 solution): 不知道这是否满足您的要求,但是我会让buildData
看起来像这样(C ++ 11解决方案):
#include <vector>
using std::vector;
/*Define TestClass*/
vector<TestClass> buildData() {
vector<TestClass> v;
v.emplace_back("A", "A");
return v;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.