标签:
[2016-05-13][C++若干问题]
int n = 5;
int a[n];
A g(){ return A();}
A c = g();
A c;
c = g();
g();
"测试用代码"
#include<iostream>
using namespace std;
class A{
public:
int a;
A(int c = 0):a(c){
cout<<"**********In A()\n";
cout<<this<<"\n";
cout<<"A:Constructor\n";
cout<<"******Out A()\n";
}
A(A & b){
cout<<"**********In Copy_A()\n";
cout<< & b <<" to "<<this<<"\n";
cout<<"B:Copy_Constructor\n";
a = b.a;
cout<<"**********Out copy_A()\n";
}
~A(){
cout<<this<<"~A\n";
}
A operator = (const A & b){
cout<<"Operator =\n";
a = b.a;
return *this;
}
};
A g(){
cout<<"In g()\n";
A c;
cout<<"before g() return\n";
return c;
}
int main(){
//A c = g();
A c;
c = g();
cout<<"C is:"<<&c<<"\n";
//g();
return 0;
}
就是在
Array operatpr +
return tmp;//Array的某变量
中返回一个对象
然后中途会进入到tmp拷贝到临时对象的复制构造函数中,但是在这个函数里面使用this查看变量,发现this的元素没有初始化,也就是没有调用构造函数(不管是默认的还是复制的)!!!
解决办法:在构造函数里面调用一次构造函数.
class qhy;
qhy a,b;
a = a + b;//(1)
a = b + 1;//(2)
a = 1 + b;//(3)
class qhy{
static int a = 0; // 非法!
static const int b = 0; //合法!
};
class qhy{
public:
const int a;
qhy(int _a):a(_a){}//合法!!
qhy(int _a){a = _a;}//非法
};
class qhy{
public:
const int a[2];//这个没办法初始化,还是使用静态成员数组吧
static const int b[2] = {1,2};//非法!!,正确姿势请看c
static const int c[2] ;
};
const int qhy::c[2] = {1,2};
ClassX::operator Type(){
//do something
return Type_Value;
}
class qhy{
public:
int a;
operator int(){return a;}
};
int main(){
qhy a;a.a = 10;
cout<<int(a);
}
class Base{
public:
int a;
Base():a(0){}
};
class qhy : public Base{
public:
int a;
qhy():a(1){}
};
int main(){
qhy a;
cout<<a.a<<" "<<a.Base::a<<"\n";
//1 0
}
非虚继承,调用了两次B的构造函数
虚继承,调用了一次B的构造函数
声明,继承前面加上virtual
class qhy :virtual public Base{};
虚继承的最高级的基类,就是上面的B,在D的构造函数中提供参数,不受B1,B2构造函数的影响
class qhy :public Base{
qhy(int a):Base(a){};
};
class qhy :public Base1,public Base2{};//先调用Base1的构造函数,在调用Base2的构造函数
必须强制转换成基类指针之后,才能访问到基类对象
小结:根据指针类型调用指针类型对应的函数,强制转换相当于加上了作用域符::
class Base{
public:
int a,b;
Base():a(0),b(1){}
};
class qhy:public Base{
public:
int b,c;
qhy():b(2),c(3){}
};
int main(){
qhy *pq;Base *pb;
qhy q;Base b;
cout<<b.a<<" "<<b.b<<" "<<q.b<<" "<<q.c<<"\n";//0 1 2 3
pb = &q;//使用基类指针引用派生类
cout<<pb->a<<" "<<pb->b<<"\n";//0 1
//cout<<pb->c<<"\n";//错误,在Base中c不存在
cout<<((qhy*)pb)->a<<" "<<((qhy*)pb)->b<<" "<<((qhy*)pb)->c<<"\n";//0 2 3,b访问到的是qhy的b
//使用派生指针引用基类
//pq = &b;//错误,类型不对
pq = (qhy*)&b;
cout<<pq->b<<pq->c;//乱码,因为b,c不存在
return 0;
}
virtual int func() = 0;
- | 基类成员属性 | public | protected | private |
---|---|---|---|---|
继承类型 | ↓继承之后的属性,属性性质→ | 所有都可见 | 类内部,友元,子类可见 | 类内部,友元可见,子类不可见 |
public | 完全不变 | public | protected | private |
protected | public变成protectd,其他保持 | protected | protected | private |
private | 全部变成private | private | private | private |
标签:
原文地址:http://www.cnblogs.com/qhy285571052/p/b0ad386ba4ac12d727389739fb9b146e.html