0

我是 C++ 新手,但在 Java 方面有一些经验。我会在 Java 中这样做:

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

但是我不知道如何在 C++ 中做到这一点,我应该保留指向 DynHashtable 的指针还是应该保留它的 Object,或者没有区别?

4

2 回答 2

3

在这种情况下,我想您不需要保留任何指针。给您的数据成员自动存储期限。它将在SymbolTable包含它的对象被构​​造时被构造,在SymbolTable对象被破坏时被破坏。

换句话说,SymbolTable完全封装并拥有DynHashtable<string>对象,拥有控制其生命周期的专有责任。

此外,在 C++ 中,您应该使用它std::string来表示字符串(您必须包含<string>标准标头才能导入其定义:

#include <string>

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

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

更新:

从评论来看,这似乎DynHastable不是默认可构造的,它的构造函数接受 anint作为其参数。在这种情况下,你必须在构造函数的初始化列表中构造你的对象:

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

public:
    SymbolTable() : hst(42) {
    //            ^^^^^^^^^
        // ...
    }
};
于 2013-04-06T13:40:08.520 回答
1

在 C++ 中,您通常将变量直接嵌入值语义,或者将变量std::shared_ptr用于引用语义。这是价值语义:

#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
    {
    }
};

这是参考语义:

#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>>())
    {
    }
};

但是您通常需要定义更多的方法,例如复制操作符、赋值运算符等。

于 2013-04-06T13:41:26.230 回答