假设我正在定义一个表面对象
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?
struct
和 class
几乎是同义词。使用您认为更清楚地表达您的意图的任何一个。至于“别的东西”,试试 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?
class
和 struct
都不需要用户定义的构造函数,但都允许它们。
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/