#includeC++的钻石继承#include #include using namespace std; class Student{ public: int num; char name[20]; int core; friend void save(); friend void view(); }; void view(Student *s2){ cout << s2->num << endl; cout << s2->name << endl; cout << s2->core << endl; } void save(Student *s2){ int i; fstream fs; //文件流对象 fs.open("user.txt",fstream::in | fstream::out |fstream::app); //目标 fs.seekg(0, ios::end); ofstream destFile("out.txt",ios::in);//以文本模式打开in.txt if(!destFile){ //打开失败 cout << "error opening destination file." << endl; } for(int i=0;i<1;i++) destFile << s2->num << " "; destFile << s2->name << " "; destFile << s2->core << " "; destFile.close(); } main(){ Student s1; cout << "please input you studentNum: " << endl; cin >> s1.num; cout << "you studentNum is : " << s1.num << endl; cout << "please input you name" << endl; cin >> s1.name; cout << "you name is :" << s1.name << endl; cout << "please input you core : " << endl; cin >> s1.core; cout << "you core is : " << s1.core << endl; view(&s1); save(&s1); }
#includeusing namespace std; class A{ int a; public: A(int n){ a=n; cout << "A::a=" << a << endl; } ~A(){ cout << "A的对象在消亡" << endl; }; }; class B{ int b; public: B(int n1,int n2){ b=n1; cout << "B::b=" << b << endl; } ~B(){ cout << "B的对象在消亡" << endl; }; }; class C:public A,public B{ int c; public: C(int n1,int n2, int n3,int n4):B(n3,n4),A(n2){ c=n1; cout << "C::c=" << c << endl; } ~C(){ cout << "C的对象在消亡" << endl; }; }; int main(){ C Cobj(1,3,5,7); return 0; }
C++ 类模板结果展示:
A::a=3
B::b=5
C::c=1
C的对象在消亡
B的对象在消亡
A的对象在消亡
//类模板中成员函数的创建时机 #includeusing namespace std; class Person1 { public: void showPerson1() { cout << "Person1 show" << endl; } }; class Person2 { public: void showPerson2() { cout << "Person2 show" << endl; } }; template class Myclass { public: T obj; //类模板中的成员函数在调用的时候才创建,所以不会报错 void func1() { obj.showPerson1(); } void func2() { obj.showPerson2(); } }; void test01() { Myclass m; m.func1(); //m.func2(); 无法调用 }; int main() { test01(); system("pause"); return 0; }
结果: Person1 show
类模板的声明还可以是template
#includeusing namespace std; class Test{ private: int n; public: Test(int i=16){ n=--i; } int Get(){ return n; } int Get()const { return(n-2); } }; int main(){ Test a; const Test b(27); cout << a.Get() << endl; cout << b.Get() << endl; return 0; }
结果 15 24



