string - C++ Passing pointer constant as parameter from main to method -
i attempting initialize variables within object, using function const pointers parameters.
i keep getting errors in many of ways attempted, here code:
class molecule { private: char s[21]; char d[21]; double w= 0; public: molecule(); void set(const char*, const char*, double); void display() const; }; int main() { int n; cout << "molecular information\n"; cout << "=====================" << endl; cout << "number of molecules : "; cin >> n; molecule *molecule = new molecule[n]; (int = 0; < n; i++) { char symbol[21]; char description[21]; double weight; molecule[i].set(&symbol,&discription,weight); //... } //implementation of class #include "molecule.h" #include <iostream> #include <cstring> void molecule::set(const char*, const char*, double) { s = &symbol; d = &discription; w = &weigth; }
my question is: how correctly call member function array of objects, using constant chars parameter, , correct way set them variables in class.
p.s: have been trying figure out long time, , posting here last resort.
there multiple errors in code
&symbol
(wheresymbol
char[21]
) yieldschar(*)[21]
, usesymbol
directly , let decaychar*
or use explicitly&symbol[0]
double weight;
uninitialized local variable, using results in undefined behavior - should initialize it:double weight = 0.0;
double w= 0;
used declare member ofclass molecule
invalid, use constructor's initializer list:molecule() : w(0.0) { } // initializes `w` `0.0`
s = symbol;
s
char[21]
,symbol
char*
not copy strings, c-style copyingstrcpy
used (note c , c++ different languages)you have called
new[]
nice , appropriate calldelete[]
, instead of relying on os cleaning after program terminates: (otherwise follow point 6)molecule *molecule = new molecule[n]; ... delete[] molecule;
if allowed use vectors, replace
molecule *molecule = new molecule[n];
std::vector<molecule> molecules(n);
if allowed use
std::string
1) objects, replacechar[21]
/char*
std::string
objects
other suggestions:
use meaningful names variables, if want explicitly distinguish private members other local variables, convention use
_
@ end of name:class molecule { private: std::string symbol_; std::string description_; double weight_;
1) need know std::string
is template wraps raw char*
, contains well-defined copying, concatenation using operator +
, important: don't need bother memory management. #include <string>
Comments
Post a Comment