您的位置:首页 > 编程语言 > C语言/C++

关于C++的疑问剖析

2015-09-04 20:50 525 查看
1)众所周知,抽象类是不存在对象的,只提供接口而不提供实现。但是抽象类能不能作为一个类指针,指向其子类的对象呢?

class Interface {
public:
virtual void fun() = 0;
};

class Implement: public Interface {
public:
void fun() {
cout<<"This is Implement object."<<endl;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
Interface *obj = new Implement();
obj->fun();
return 0;
}


  结论:能。抽象类不能拥有自己的类对象,但是,可以定义抽象类指针指向其子类的对象。

2)指向指针的指针 两种最常见的情形:(数组的名字会退化成其首元素的指针。

2.1 指针数组:

class Shape {
public:
void testFunc() {
cout<<"Shape::testFunc()"<<endl;
}
//...
};

Shape *picture[10];

int _tmain(int argc, _TCHAR* argv[])
{
Shape **temp = picture;
Shape *p = *temp;
p->testFunc();
return 0;
}




2.2

void scanTo(const char **p, char ch) {
while (**p && **p != ch) {
++*p;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char s[] = "hello, World";
const char *cp = s;
scanTo(&cp, ',');//将指针cp移动第一个“,”出现的位置
cout<<*cp<<endl;
return 0;
}


3)仿函数

//仿函数 加法
template <class T>
struct plus {
T operator() (const T& x, const T& y) const {
return x+y;
}
};

//仿函数 减法
template <class T>
struct minus {
T operator() (const T& x, const T& y) const {
return x-y;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
//以下产生仿函数对象
plus<int> plusObj;
minus<int> minusObj;
//以下使用仿函数,就像使用一般函数一样
cout<<plusObj(3,5)<<endl;
cout<<minusObj(3,5)<<endl;

//以下直接产生仿函数的临时对象(第一对小括号),并调用之(第二对小括号)
cout<<plus<int>()(3,5)<<endl;
cout<<minus<int>()(3,5)<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: