1.类(class)私有成员可以被类成员函数访问,不区分成员在哪个实例(instance)里。
例如:
class p{
private kk;
void display(P h)
{
cout<<h.kk;
}
}
......
P t,u;
t.dispaly(u);
2.类的继承注意
(1)对象模型
-
私有成员还是会继承,只不过是隐藏了,通过调用基类成员函数还是可以调用基类的私有成员。如用sizeof(派生类),也是包含基类的私有成员内存大小的!基类和其派生类共享该基类的静态成员变量内存!
-
当用派生类的创建对象时,也会调用基类的构造函数。构造顺序:基类—派生类 析构顺序:派生类—基类
-
所以:
#include <iostream>
using namespace std;
class rectangle
{
public:
int length,width;
rectangle(int a,int b)
{
length=a;
width=b;
}
void area()
{
cout<<"面积:"<<length*width<<endl;
}
};
class cuboid: public rectangle
{
public:
int height;
cuboid(int,int,int);
void volume()
{
cout<<"体积:"<<height*length*width<<endl;
}
};
cuboid::cuboid(int a,int b,int c)
{ -----------这里报错
length=a;
width=b;
height=c;
}
int main()
{
rectangle pp(2,2);
cuboid kk(2,3,6);
pp.area();
kk.volume();
return 0;
}
报错:
no matching function for call to 'rectangle::rectangle()'
- 错误原因:基类和派生类都有自己定义的构造函数并且有参数,并且都会调用,没有指示基类的构造函数如何,则出错。
- 正确的写法如下:
#include <iostream>
using namespace std;
class rectangle
{
public:
int length,width;
rectangle(int a,int b)
{
length=a;
width=b;
}
void area()
{
cout<<"面积:"<<length*width<<endl;
}
};
class cuboid: public rectangle
{
public:
int height;
cuboid(int,int,int);
void volume()
{
cout<<"体积:"<<height*length*width<<endl;
}
};
cuboid::cuboid(int a,int b,int c):rectangle(a,b) ------改动
{
height=c; ----这里可以少写部分内容
}
int main()
{
rectangle pp(2,2);
cuboid kk(2,3,6);
pp.area();
kk.volume();
return 0;
}
- 这样就可以顺利运行
2.抽象类
类中有一个或者多个纯虚函数;
纯虚函数:例如:
virtual void j()=0;
特点:
(1)抽象类无法实例化对象
(2)若子类不对继承来的抽象类中的纯虚函数重写,也叫抽象类,也不能实例化对象;
3.输入输出
cout.width()
cout.width(要设置的宽度) //等同于setw(要设置的宽度)(setw在头文件iomanip中)
当输出内容位数不超过所设置的位数是,默认右对齐,前面补空格;
超出时cout.width没有效果。
每次需要输出时都要指定一下width,否则,没有效果。
例子:
int main()
{
int i;
i=15;
while(i<=20)
{
cout.width(5);
cout<<cout.width()<<endl;
cout<<"qwertdg"<<endl;
cout<<cout.width()<<endl;
cout.width(1);
cout<<cout.width()<<endl;
cout<<"qwertdf"<<endl;
cout<<cout.width()<<endl;
i++;
cout.width
}
输出:
qwertdf
0
5
qwertdg
0
1
qwertdf
0
5
qwertdg
0
1
qwertdf
0
5
qwertdg
0
1
qwertdf
0
5
qwertdg
0
1
qwertdf
0
4.c++文件操作取不到字符问题
在建立新的文件关系之前,一定要先关闭上一次操作的close!
如:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
char a;
ofstream ofs;
ifstream ifs;
ofs.open("123.dat");
int i=21;
cout<<ofs<<endl;
if(ofs)
{
while(i<=51)
{
if(i%2==0)
{
ofs<<i<<" ";
}
i++;
}
}
else cout<<"error!"<<endl;//一定要提前关闭否则下面的get读不出来!
ofs.close();
ifs.open("123.dat",ios::in|ios::out);
i=0;
if(ifs)
{
while(ifs.get(a)!=0)
{
if(i%5==0)
cout<<"\n";
cout<<a;
i++;
}
cout<<"输出-1"<<a<<"3";
}
else cout<<"error!"<<endl;
ifs.close();
return 0;
}
5.文件输入输出注意哦拉嘿嘿!!!!
文件在与另一个输出或者输出对象使用,即使你不使用了,她(这个对象ofstream和ifstream)还是会与这个文件有着联系,当你再次需要读入或者写出时需要使用此文件,必须先关闭在使用,否则会输入或者输出错误!
但是不知道为什么,这个问题先留着!!
6.数组,擦,今天遇到的问题,2020-6-2
比如:
int a[10];//10个内存空间,不包括最后一个a[10];
我是这么想的;
当int a[10]时,里面的10代表的是去申请10个内存空间,如果写9的话,就少申请了一个,就错了!
但是下标是从0开始的,符合这个公式:a+i*sizeof(int);一共10个int地址空间!!!
**
7.静态成员函数只能访问静态成员数据、其他静态成员函数和类外部的其他函数。
**