这个问题已经在c# /. net上下文中提出过了。

现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。

我将从一个明显的区别开始:

如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。

我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。


当前回答

类的成员默认为private, struct的成员默认为public。

例如,程序1编译失败,程序2运行正常。

// Program 1
#include <stdio.h>
 
class Test {
    int x; // x is private
};

int main()
{
  Test t;
  t.x = 20; // compiler error because x is private
  getchar();
  return 0;
}
// Program 2
#include <stdio.h>
 
struct Test {
    int x; // x is public
};

int main()
{
  Test t;
  t.x = 20; // works fine because x is public
  getchar();
  return 0;
}

从类/结构派生结构时,基类/结构的默认访问说明符为public。派生类时,默认访问说明符为private。

例如,程序3编译失败,程序4工作正常。

// Program 3
#include <stdio.h>
 
class Base {
public:
    int x;
};
 
class Derived : Base { }; // is equivalent to class Derived : private Base {}
 
int main()
{
  Derived d;
  d.x = 20; // compiler error because inheritance is private
  getchar();
  return 0;
}
// Program 4
#include <stdio.h>
 
class Base {
public:
    int x;
};
 
struct Derived : Base { }; // is equivalent to struct Derived : public Base {}
 
int main()
{
  Derived d;
  d.x = 20; // works fine because inheritance is public
  getchar();
  return 0;
}

其他回答

另一件需要注意的事情是,如果你更新了一个有结构的遗留应用程序来使用类,你可能会遇到以下问题:

旧代码有结构,代码被清理,这些被更改为类。 然后将一两个虚函数添加到新更新的类中。

当虚函数在类中时,编译器会在内部添加额外的指针指向类数据,以指向函数。

这将如何打破旧的遗留代码是,如果在旧代码中的某个地方使用memfill将结构清除为零,这也将破坏额外的指针数据。

这里有一个很好的解释:http://carcino.gen.nz/tech/cpp/struct_vs_class.php

所以,再强调一次:在c++中,结构体与类是相同的,除了结构体的成员默认具有公共可见性,而类的成员默认具有私有可见性。

oops中structure和class关键字的主要区别在于,structure中没有public和private成员声明。数据成员和成员函数可以定义为public、private和protected。

另一个主要区别是模板。据我所知,你可以在定义模板时使用类,但不能定义结构。

template<class T> // OK
template<struct T> // ERROR, struct not allowed here

类的成员默认为private。Struct的成员默认为public。除此之外,没有其他区别。还有这个问题。