c++ - How to store a variable in a header, to use in the main cpp? -
i tried asking question, bit more fuzzy on details, arrived home , hope can explain myself better.
say, have class, in case, testclass
, declared constructor , methods in testclass.h
already. now, want create new array of these elements, , store them somewhere, load in main.cpp
, when want to.
what tried doing, is, doing in new header, called contents table.h
. here, tried making array of these testclass
elements. however, don't know, how go 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 contents table, want store data, manually write in, had 2 ideas doing this, not sure 1 feasible:
first idea:
contentstable.h
#include "testclass.h" testclass* builddata(void) { testclass* world = new testclass[5]; world[0] = testclass("a", "a"); //etc, fill rest up. return world; }
and in main.cpp, i'd call function, like
#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 again in main.cpp, second 1 things, i'm trying redeclare dataarray2, when try giving 1 if elements value. (again, i'm sure it's fault this, sorry, if seems banal code, haven't been learning long.)
not sure if meets requirements, i'd make builddata
(c++11 solution):
#include <vector> using std::vector; /*define testclass*/ vector<testclass> builddata() { vector<testclass> v; v.emplace_back("a", "a"); return v; }
Comments
Post a Comment