c++ - 在 C++ 中,定义一个非常简单的对象的最有效方法是什么

标签 c++ class struct

假设我正在定义一个表面对象

class surface
{
private:
    vector<point> points_;
    vector<hexFace> hexFaces_;
}

我已经写了一个point类,很有必要,但是hexFace其实很简单,就是四个point的列表< strong>labels,即int[4]。而且我不需要对它做任何复杂的操作。

所以我的问题是:定义这样一个 hexFace 对象的最有效方法是什么。我应该使用结构,还是我最好去上课或其他什么?你会怎么办?谢谢

如果我需要和类一起去,我可以在当前类中以嵌套的方式定义另一个类吗?如果可以的话,我是否也必须在此文件中编写其构造函数?

结构体是否需要构造函数来初始化它?

最佳答案

你问了几个问题:

what is the most efficient way in defining such an hexFace object.

对于您选择的任何解决方案,运行时效率都大致相同。代码行效率,或维护者-程序员-脑力效率可能更有值(value)。

如果您仅限于使用 C++11 之前的功能,我会使用:

struct hexFace {
  int labels_[4];
};

如果您可以使用 C++11 功能,请尝试:

class surface
{
private:
    std::vector<point> points_;
    std::vector<std::array<int, 4>> hexFaces_;
}

Should I use struct, or I'd better go with a class or anything else?

structclass 几乎是同义词。使用您认为更清楚地表达您的意图的任何一个。至于“别的东西”,试试 std::array

can I defining another class in the current class in a nesting way?

是的,你可以。尝试:

class surface
{
private:
    class hexFace { public: int lables[4]; };
    vector<point> points_;
    vector<hexFace> hexFaces_;
};

If I can, do I have to write its constructors within this file also?

您可以,或者您可以选择在其他地方编写它,或者您可以选择完全省略用户定义的构造函数。

下面是内联的写法:

class surface {
public:
    class hexFace { public: hexFace() { std::cout << "inline constructor!\n" } };
}

外部写法

class surface {
  public:
  class hexFace {
    public:
      hexFace();
  };

// in another file ...
surface::hexFace::hexFace() { std::cout << "extern constructor\n"; }

Does a struct need a constructor to initialize it?

classstruct 都不需要用户定义的构造函数,但都允许它们。

struct X {
  X() { std::cout << "in struct constructor!\n"; }
};
class Y {
  public: 
    Y() { std::cout << "in class constructor!\n"; }
};

关于c++ - 在 C++ 中,定义一个非常简单的对象的最有效方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14241341/

相关文章:

java - 如何在另一个方法中调用带有参数的方法?

c++ - 将私有(private)静态数组作为参数传递给 C++ 中的公共(public)成员函数?

c - 如何正确清除结构数组

C++ 线程安全总结

c++ 没有合适的从 "Camera"到 "Actor *"的转换函数

c++ - 将类声明为类的一部分的问题

MATLAB:嵌套函数和结构

c - 将字符串分配给某物

c++ - 逗号在数组和结构初始化中的意义是什么?

c++ - OpenCV VideoCapture 输出图像剪切到左上四分之一