参见《C++ Primer 中文版》的57页,用class和struct关键字定义类的唯一差别在于默认访问级别:默认情况下,struct的成员为public,而class的成员为private。另外一个区别:“class”这个关键字还用于定义模板参数,就像“typename”。但关键字“struct”不用于定义模板参数。
这是一个很简单的面试题,可是曾经引起一大些的争论,详细的争论请看下帖:
http://topic.csdn.net/u/20090731/19/27813e69-ec2e-4798-98b3-f59fafcfbdbf.html,个人感觉最有力的理解就是试一下42楼的程序:
#include <iostream>
struct Test {
//private:
Test() { std::cout << "Test." << std::endl; }
virtual v_proc(){std::cout << "Test.v_proc." << std::endl; }
~Test() { std::cout << "~Test." << std::endl; }
int operator +(const int a){return a+1;}
};
struct Test_CH : public Test
{
//private:
Test_CH() { std::cout << "Test_CH." << std::endl; }
virtual v_proc(){std::cout << "Test_CH.v_proc." << std::endl; }
~Test_CH() { std::cout << "~Test_CH." << std::endl; }
};
class CTest {
public:
CTest(){std::cout << "CTest." << std::endl;}
~CTest(){std::cout << "~CTest." << std::endl;}
};
int main() {
Test *o_Test;
o_Test=new Test;
o_Test->v_proc();
std::cout << "o_Test->operator +(5)="<<o_Test->operator+(5)<< std::endl;
delete o_Test;
Test_CH *o_Test_CH;
o_Test_CH=new Test_CH;
o_Test_CH->v_proc();
std::cout << "o_Test_CH->operator +(6)="<<o_Test_CH->operator+(6)<< std::endl; delete o_Test_CH; CTest *o_CTest;
o_CTest=new CTest;
delete o_CTest;
return 0;
}
运算结果为:
Test.
Test.v_proc.
o_Test->operator +(5)=6
~Test.
Test.
Test_CH.
Test_CH.v_proc.
o_Test_CH->operator +(6)=7
~Test_CH.
~Test.
CTest.
~CTest.
Press any key to continue。