简体   繁体   中英

C++ initializing a class member object

I am new to C++, but have some experience in Java. I would do this in Java:

public Class SymbolTable{
   private DynHashtable<String> hst;
   public SymbolTable(){
      hst = new DynHashtable<String>();
   }
}

But I don't know how I can do that in C++, should I keep a pointer to DynHashtable or should I keep an Object of it, or there is no difference??

In this case, I guess you don't need to keep any pointer. Give your data member automatic storage duration . It will be constructed when the SymbolTable object that contains it is constructed, and destructed when the SymbolTable object is destructed.

In other word, SymbolTable entirely encapsulates and owns the DynHashtable<string> object, having the exclusive responsibility of controlling its lifetime.

Also, in C++ you should use std::string for representing strings (you must include the <string> standard header to import its definition:

#include <string>

class SymbolTable {
private:
    DynHashtable<std::string> hst;

public:
    SymbolTable() {
        // ...
    }
};

UPDATE:

From the comments, it seems that DynHastable is not default-constructible, and its constructor accepts an int as its parameter. In this case, you have to construct your object in the constructor's initialization list:

class SymbolTable {
private:
    DynHashtable<std::string> hst;

public:
    SymbolTable() : hst(42) {
    //            ^^^^^^^^^
        // ...
    }
};

In C++ you usually embed the variable directly for value-semantics or you use a std::shared_ptr for reference-semantics. Here's value-semantics:

#include <string>
#include <unordered_set> // the equivalent of DynHashtable AFAICT

class SymbolTable
{
private:
    std::unordered_set<std::string> hst;
public:
    SymbolTable() // automatically calls the default ctor for hst
    {
    }
};

and here's reference-semantics:

#include <string>
#include <unordered_set> // the equivalent of DynHashtable AFAICT
#include <memory>        // for std::shared_ptr / std::make_shared

class SymbolTable
{
private:
    std::shared_ptr<std::unordered_set<std::string>> hst;
public:
    SymbolTable()
      : hst(std::make_shared<std::unordered_set<std::string>>())
    {
    }
};

but you usually need to define more methods like a copy-ctor, assignment operators, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM