在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
c++中类和结构的区别是:
结构成员和基类/结构在默认情况下是公共的。 默认情况下,类成员和基类/结构是私有的。
类和结构都可以混合使用public、protected和private成员,可以使用继承,也可以有成员函数。
我向你推荐:
对于没有任何类样特性的普通旧数据结构使用struct; 在使用私有或受保护成员、非默认构造函数和操作符等特性时使用类。
其他回答
正如每个人所说,唯一真正的区别是默认访问。但是,当我不想对简单的数据类进行任何形式的封装时,即使实现了一些helper方法,我也会特别使用struct。例如,当我需要这样的东西时:
struct myvec {
int x;
int y;
int z;
int length() {return x+y+z;}
};
从技术上讲,这两者在c++中是相同的——例如,结构体可能具有重载操作符等。
然而:
当我希望同时传递多种类型的信息时,我使用结构体 当我处理一个“功能性”对象时,我使用类。
希望能有所帮助。
#include <string>
#include <map>
using namespace std;
struct student
{
int age;
string name;
map<string, int> grades
};
class ClassRoom
{
typedef map<string, student> student_map;
public :
student getStudentByName(string name) const
{ student_map::const_iterator m_it = students.find(name); return m_it->second; }
private :
student_map students;
};
例如,我在这里的get…()方法中返回一个struct student -喜欢。
什么时候你会选择使用struct 在c++中什么时候使用类?
我在定义函子和POD时使用struct。否则我就用class。
// '()' is public by default!
struct mycompare : public std::binary_function<int, int, bool>
{
bool operator()(int first, int second)
{ return first < second; }
};
class mycompare : public std::binary_function<int, int, bool>
{
public:
bool operator()(int first, int second)
{ return first < second; }
};
当我需要创建POD类型或函子时,我使用结构体。
现有的答案中有很多误解。
class和struct都声明一个类。
是的,您可能必须在类定义中重新安排访问修改关键字,这取决于您用于声明类的关键字。
但是,除了语法之外,选择一种而不是另一种的唯一原因是惯例/风格/偏好。
有些人喜欢对没有成员函数的类坚持使用struct关键字,因为最终的定义“看起来像”C中的简单结构。
类似地,有些人喜欢对具有成员函数和私有数据的类使用class关键字,因为它表示“类”,因此看起来像他们最喜欢的面向对象编程书籍中的示例。
实际上,这完全取决于您和您的团队,这对您的程序没有任何影响。
下面这两个类除了名字以外在其他方面都是完全等价的:
struct Foo
{
int x;
};
class Bar
{
public:
int x;
};
你甚至可以在重新声明时切换关键字:
class Foo;
struct Bar;
(虽然这将破坏Visual Studio构建由于不一致,所以编译器将发出一个警告,当你这样做。)
下面的表达式都为true:
std::is_class<Foo>::value
std::is_class<Bar>::value
不过,请注意,在重新定义时不能切换关键字;这只是因为(根据单定义规则)跨翻译单元的重复类定义必须“由相同的标记序列组成”。这意味着你甚至不能交换const int成员;,并且与类或结构的语义无关。