C++中, struct和class的差别,struct默认成员函数及数据成员是公有的, 而class是私有的,还有其它么?

at_yuan2 2004-11-23 09:31:48
C++中, struct和class的差别,struct默认成员函数及数据成员是公有的, 而class是私有的,还有其它么?
本人以前认为,struct与class的区别就是如标题所说,
最近注意到, class的挎贝构造函数可以返回自身的引用:如
class CTClass
{
public:
.............
CTClass(const CTClass& other)
{
m_nValue = other.m_nValue;
return *this; //class 可以return返回自身的引用。如果是struct, 则通不过编译。
}

private:
int m_nValue;
};

但如果是struct, 则是通不过编译的(本人只有VC, 不知其它编译器通的过不?), 即,
用struct, 它的挎贝构造函数是不允许有(return)返回值的, 奇怪的是,虽然没有返回引用,但还是可以像class那象得到返回的引用。

详细一点说吧,举个例子:
//测试结构
typedef struct _tagTestStruct
{
_tagTestStruct()
{
m_dwOver = 0;
m_b = 0;
}

_tagTestStruct(int b, ULONG dwOver)
{
m_b = b;
m_dwOver = dwOver;
}

_tagTestStruct(const _tagTestStruct& other)
{
m_b = other.m_b;
m_dwOver = other.m_dwOver;
//注意这里不能 return *this; ????????????? 而class是充许的.
}

BOOL operator ==(const _tagTestStruct& other) const
{
if ((m_b == other.m_b) &&
(m_dwOver == other.m_dwOver))
{
return TRUE;
}
return FALSE;
}

_tagTestStruct& operator =(const _tagTestStruct& other)
{
m_b = other.m_b;
m_dwOver = other.m_dwOver;
return *this;
}

int m_b;
ULONG m_dwOver;
}TESTSTRUCT;

请问,class 与struct 在C++标准里,所有的差别???
...全文
244 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
大雾 2004-11-23
  • 打赏
  • 举报
回复
还有模板不支持struct
kingzai 2004-11-23
  • 打赏
  • 举报
回复
C++中声明一个struct,几乎等同于声明一个class,它具有class所具有的一切性质,包括继承,多态,而且也支持模板技术。稍微有区别的一点就是:C++中声明一个新的型别,如果不需要虚拟函数,不需要构造,析构方法,那么声明为struct要比声明为class更高效和简洁,因为编译器内部会对此进行分析并且优化。
DentistryDoctor 2004-11-23
  • 打赏
  • 举报
回复
struct默认成员函数及数据成员是公有的, 而class是私有的,其它的差别,不清楚。结构的拷贝构造函数也可以返回自身的引用。
DentistryDoctor 2004-11-23
  • 打赏
  • 举报
回复
CTClass(const CTClass& other)
=>
const CTClass& CTClass(const CTClass& other)
老夏Max 2004-11-23
  • 打赏
  • 举报
回复
我也说不清!可能就是继承性,操作函数、虚函数等等吧

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧