简体   繁体   English

C ++初始化类成员对象

[英]C++ initializing a class member object

I am new to C++, but have some experience in Java. 我是C ++的新手,但是有一些Java经验。 I would do this in Java: 我会在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?? 但是我不知道如何在C ++中做到这一点,我应该保持指向DynHashtable的指针还是应该保持它的对象,或者没有区别?

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. 构造包含它的SymbolTable对象时将对其进行构造,而销毁SymbolTable对象时将对其进行破坏。

In other word, SymbolTable entirely encapsulates and owns the DynHashtable<string> object, having the exclusive responsibility of controlling its lifetime. 换句话说, SymbolTable完全封装并拥有DynHashtable<string>对象,并具有控制其生存期的专有责任。

Also, in C++ you should use std::string for representing strings (you must include the <string> standard header to import its definition: 同样,在C ++中,您应该使用std::string表示字符串(必须包含<string>标准头文件才能导入其定义:

#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. 从注释来看, DynHastable似乎不是默认可构造的,并且其构造函数接受int作为其参数。 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. 在C ++中,通常将变量直接嵌入值语义中,或者将std::shared_ptr用作引用语义。 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. 但是您通常需要定义更多的方法,例如copy-ctor,赋值运算符等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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