c++ - initiating class as a member of struct -
im trying create struct class member inside:
.h file:
class { public: struct result { int x; ugraph g; <------ class definition }; result m_tempstructresult; a:a(void); void function(); }
.cpp file
a::a() { } void a::function() { ugraph graph(10); <---- object has receive value ... //manipulations on graph ... m_tempstructresult.g = graph; }
the compilation error is:
error c2512: 'a::result' : no appropriate default constructor available
so problem guess lack of default constructor, added this:
struct result { result::result(int graph_size=0) : g(graph_size){ } int x; ugraph g; };
and problem solved.
my question if there way initiate class ugraph g inside constructor of class a? , not inside member struct?
thanks.
yes, use initializer list in constructor of result
:
result::result() : g(0) // have insert integer here { }
another way in c++11 give default value inside class:
struct result { ugraph g = ugraph(10); };
for small demonstration, see here.
edit @othmanbenchekroun, believe understood question:
so here example code, uses aggregate initialization in order initialize members of result
(without changing constructor of latter).
struct g { g(int) {} }; struct result { int x; g g; }; struct { a() : m_tempstructresult{1, g(1)} {} result m_tempstructresult; }; int main() { a{}; }
another demo here.
this not mean, however, suggest this. rather give result
appropriate default constructor. otherwise, might become unusable.
Comments
Post a Comment