下面是引用enjoyo于2005-08-29 11:21发表的:
class 和struct有以下的不同
1.class的成员变量和函数有私有保护公共这份,struct没有
2.class可以继承,struct不可以
3.class大多数是堆分配,struct是栈分配,这一点在c++中不是很明显,因为在c++中class也可以是栈分配,但在其他语言,如C#就不一样了
又来一个误导观众的,呵呵。
首先明确,大家要讨论的是 c++里的 struct和class吧?不要再拿 c里的struct和c++里的class来说事了。
给你做了个例子,你自己编译去,然后再告诉我你的1,2,3点,错在什么地方?
-------------------------------
// struct.h
//
using namespace std;
class A
{
public:
virtual void output();
private:
int i;
};
struct B: A //这是继承吧?
{
public:
void output();
private:
int j; //这是私有吧?
};
-------------------------------
// struct.cpp
//
#include "stdafx.h"
void A::output()
{
cout<<"this is A";
}
void B::output()
{
cout<<"this is B";
}
-------------------------------
// stdafx.h : 标准系统包含文件的包含文件,
// 或是常用但不常更改的项目特定的包含文件
//
#pragma once
#include <iostream>
#include <tchar.h>
// TODO: 在此处引用程序要求的附加头文件
#include "struct.h"
-------------------------------
// stdafx.cpp : 只包括标准包含文件的源文件
// testStruct.pch 将成为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
//引用任何所需的附加头文件,而不是在此文件中引用
-------------------------------
// testStruct.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
A* b=new B(); //这是分配在heap还是stack?
b->output();
delete b;
return 0;
}