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

  1. &symbol (where symbol char[21]) yields char(*)[21], use symbol directly , let decay char* or use explicitly &symbol[0]

  2. double weight; uninitialized local variable, using results in undefined behavior - should initialize it: double weight = 0.0;

  3. double w= 0; used declare member of class molecule invalid, use constructor's initializer list:

    molecule() : w(0.0) { } // initializes `w` `0.0` 
  4. s = symbol; s char[21] , symbol char* not copy strings, c-style copying strcpy used (note c , c++ different languages)

  5. you have called new[] nice , appropriate call delete[] , instead of relying on os cleaning after program terminates: (otherwise follow point 6)

    molecule *molecule = new molecule[n]; ... delete[] molecule; 
  6. if allowed use vectors, replace molecule *molecule = new molecule[n]; std::vector<molecule> molecules(n);

  7. if allowed use std::string1) objects, replace char[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

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -