在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
类。
默认情况下,类成员是私有的。
class test_one {
int main_one();
};
等于
class test_one {
private:
int main_one();
};
所以如果你尝试
int two = one.main_one();
我们将得到一个错误:main_one是私有的,因为它不可访问。我们可以 通过指定它的公共ie来初始化它来解决它
class test_one {
public:
int main_one();
};
结构体。
struct是一个类,其成员默认为public。
struct test_one {
int main_one;
};
意味着main_one是私有的,即
class test_one {
public:
int main_one;
};
我用struct表示数据结构,其中成员可以取任何值 那样容易些。
其他回答
摘自c++ FAQ Lite:
The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults. struct and class are otherwise functionally equivalent. OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.
我只在需要保存一些没有任何成员函数与之关联的数据(对成员数据进行操作)并直接访问数据变量时使用struct。
从文件和套接字流等读取/写入数据。在函数参数太多且函数语法看起来太冗长的结构中传递函数参数。
从技术上讲,类和结构之间没有太大的区别,除了默认的可访问性。 更重要的是,它取决于你如何使用它的编程风格。
从技术上讲,这两者在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 -喜欢。
类。
默认情况下,类成员是私有的。
class test_one {
int main_one();
};
等于
class test_one {
private:
int main_one();
};
所以如果你尝试
int two = one.main_one();
我们将得到一个错误:main_one是私有的,因为它不可访问。我们可以 通过指定它的公共ie来初始化它来解决它
class test_one {
public:
int main_one();
};
结构体。
struct是一个类,其成员默认为public。
struct test_one {
int main_one;
};
意味着main_one是私有的,即
class test_one {
public:
int main_one;
};
我用struct表示数据结构,其中成员可以取任何值 那样容易些。
我从来不在c++中使用struct。
我无法想象在需要私有成员时使用结构体的场景,除非您故意试图混淆。
使用结构体似乎更像是一种如何使用数据的语法指示,但我宁愿只创建一个类,并尝试在类的名称中显式地表示它,或通过注释。
E.g.
class PublicInputData {
//data members
};
推荐文章
- 如何构建和使用谷歌TensorFlow c++ api
- 接口方法的最终参数-有什么意义?
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在STL地图中,使用map::insert比[]更好吗?
- 在Java中使用“final”修饰符
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- 我怎么知道什么时候创建一个接口?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?
- 什么时候使用Struct vs. OpenStruct?
- 解析c++中的命令行参数?