这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
当前回答
类和结构之间的区别是关键字之间的区别,而不是数据类型之间的区别。这两个
struct foo : foo_base { int x;};
class bar : bar_base { int x; };
两者都定义了一个类类型。这里关键字的区别在于默认访问权限的不同:
Foo::x是公共的,foo_base是公共继承的 Bar::x是私有的,bar_base是私有继承的
其他回答
这只是一种惯例。可以创建结构来保存简单的数据,但稍后会随着成员函数和构造函数的添加而发展。另一方面,在struct中看到public: access之外的东西是不寻常的。
我发现了另一个不同。如果在类中没有定义构造函数,编译器将定义一个。但是在struct中,如果你没有定义构造函数,编译器也不会定义构造函数。因此,在某些情况下,我们确实不需要构造函数,struct是一个更好的选择(性能技巧)。 对不起,我的英语不好。
. In classes all the members by default are private but in structure members are public by default. There is no term like constructor and destructor for structs, but for class compiler creates default if you don't provide. Sizeof empty structure is 0 Bytes wer as Sizeof empty class is 1 Byte The struct default access type is public. A struct should typically be used for grouping data. The class default access type is private, and the default mode for inheritance is private. A class should be used for grouping data and methods that operate on that data. In short, the convention is to use struct when the purpose is to group data, and use classes when we require data abstraction and, perhaps inheritance. In C++ structures and classes are passed by value, unless explicitly de-referenced. In other languages classes and structures may have distinct semantics - ie. objects (instances of classes) may be passed by reference and structures may be passed by value. Note: There are comments associated with this question. See the discussion page to add to the conversation.
类的成员默认为private。Struct的成员默认为public。除此之外,没有其他区别。还有这个问题。
结构的成员默认为public,类的成员默认为private。 结构从另一个结构或类的默认继承是公共的。类从其他结构或类的默认继承是私有的。
class A{
public:
int i;
};
class A2:A{
};
struct A3:A{
};
struct abc{
int i;
};
struct abc2:abc{
};
class abc3:abc{
};
int _tmain(int argc, _TCHAR* argv[])
{
abc2 objabc;
objabc.i = 10;
A3 ob;
ob.i = 10;
//A2 obja; //privately inherited
//obja.i = 10;
//abc3 obss;
//obss.i = 10;
}
这是在VS2005上。