趨勢科技的筆試
- 面試筆試
- 關注:1.87W次
1、#include <stdio.h>
class A{
public:
A(){func(0);};
virtual void func(int data){printf("A1:%d",data);}
virtual void func(int data) const{printf("A2:%d",data);}
void func(char *str){printf("A3:(%s)",str);}
};
class B:public A{
public:
void func(){printf("B1:%s","");}
void func(int data){printf("B2:%d",data);}
void func(char *str){printf("B3:(%s)",str);}
};
int main()
{
A *pA;
B b;
const A *pcA;
pA=&b;
pA->func(1);
pA->func("test");
A()(1);
pcA=&b;
pcA->func(2);
return 0;
}
程序運行的結果:
A1:0
B2:1
A3:(test)
A1:0
A1:1
A2:2
1)
基類的指針指向派生類對象:那麼該指針只能夠調用基類所定義的函數,但是如果該函數為虛函數,則調用該派生類自己的成員函數。(B2:1)
2)
如果以派生類的指針指向基類對象,則必須事先做明顯的轉型操作,但是這種做法很危險。
2、
include <iostream.h>template <typename T>
void func(const int &t)
{
cout<<t+100<<endl;
}
template<typename T>
void func(const T&t)
{
cout<<t<<endl;
}
int main()
{
func(10.3);
func(1000);
return 0;
}
程序運行結果:
10.3
1000
如果上述函數改為
include <iostream.h>void func(const int &t)
{
cout<<t+100<<endl;
}
template<typename T>
void func(const T&t)
{
cout<<t<<endl;
}
int main()
{
func(10.3);
func(1000);
return 0;
}
則程序的運行結果為:
10.3
1100
如果使用函數的非模板形式,不能在前面加上template關鍵字。
3、
改錯:
include <iostream.h>class klass
{
public:
klass(){}
private:
~klass(){}
void func(int n){
cout<<"klass!!"<<endl;
} public:
void test(){
func(100);
}
};
int main()
{
klass k;
();
return 0;
}
運行後程序顯示:error C2248: 'klass::~klass': cannot access private member declared in class 'klass'
證明析構函數的屬性必須為public。
但是,如果把klass k改為klass* pk; pk=new klass; pk->test();程序通過,但是klass不能釋放
- 文章版權屬於文章作者所有,轉載請註明 https://yhjlw.com/zh-mo/mian/bishi/zjv82.html