今天,我对比了C++中结构体和类的区别,发现了以下几点:
- 在结构体中,默认情况下成员是公有的,而在类中是私有的。
- 在结构体中,默认情况下继承是公有的,而在类中是私有的。
- 类可以参与模板,而结构体不能。
template<struct T> void fun(T i)
{
cout<<i<<endl;
}
int main()
{
int i=10;
fun<int>(i);
return 0;
}
它会给出以下错误:
prog.cpp:4: error: ‘struct T’ is not a valid type for a template constant parameter
prog.cpp: In function ‘void fun(T)’:
prog.cpp:4: error: ‘i’ has incomplete type
prog.cpp:4: error: forward declaration of ‘struct T’
prog.cpp: In function ‘int main()’:
prog.cpp:12: error: no matching function for call to ‘fun(int&)’
然而,如果将 struct 替换为 class,它就可以完美地运作。详见这里:http://ideone.com/K8bFn
除了上述差异之外,在我的代码中,如果我将 class
替换为 struct
,不需要进行任何其他修改,代码就能够完美运行。
现在,我想知道是否还有其他差异我所不知道的,需要注意吗?
struct
作为模板参数中typename
的等价词,但这只是一个关键字而已。 - David Rodríguez - dribeas