类与对象
在成员访问模式中:
public 表示共有;类的数据成员和函数可以被该类对象和派生类访问。
private 私有型;自己的类可以访问,但派生类不能访问。
protected 保护型;自身类和派生类可以访问相当于自身的private型成员,它同private的区别就是在对待派生类的区别上。
C++中 public,protected, private 访问标号小结
第一:private, public, protected 访问标号的访问范围。
private:只能由1.该类中的函数、2.其友元函数访问。不能被任何其他访问,该类的对象也不能访问。
protected:可以被1.该类中的函数、2.子类的函数、以及3.其友元函数访问。但不能被该类的对象访问。
public:可以被1.该类中的函数、2.子类的函数、3.其友元函数访问,也可以由4.该类的对象访问。
注:友元函数包括3种:设为友元的普通的非成员函数;设为友元的其他类的成员函数;设为友元类中的所有成员函数。
第二:类的继承后方法属性变化。
private 属性不能够被继承。
使用private继承,父类的protected和public属性在子类中变为private;
使用protected继承,父类的protected和public属性在子类中变为protected;
使用public继承,父类中的protected和public属性不发生改变;如下所示:
public: protected: private:
public继承 public protected 不可用
protected继承 protected protected 不可用
private继承 private private 不可用
protected继承和private继承能降低访问权限。
————————————————
原文链接:https://blog.csdn.net/weixin_50849959/article/details/116595077
动态的内存分配
#include "iostream"
using namespace std;
class Shape
{
public:
Shape(double a = 0.0, double b = 0.0)
{
length = a;
height = b;
}
~Shape() {
cout << "this class is end!" << endl;
}
void getLength(double l)
{
length = l;
}
void getHeight(double h)
{
height = h;
}
virtual double getarea() = 0;
protected:
double length;
double height;
};
class Circle :public Shape {
public:
Circle(double l = 1.0, double w = 1.0) {
length = l;
height = w;
}
double getarea() {
return 3.14 * length * height / 4;
}
};
class Rectangle :public Shape {
public:
Rectangle(double l = 0, double h = 0) {
height = h;
length = l;
}
double getarea() {
return height * length;
}
};
void func()
{
int** arr;
arr = new int* [5];
for (int i = 0; i < 5; i++) {
arr[i] = new int[5];
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
arr[i][j] = i * 5 + j;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < 5; i++) {
delete[] arr[i];
}
delete[] arr;
}
int main()
{
func();
cout << endl;
int* test = new int;
*test = 5;
cout << "=== Storage alloction of single var ===" << endl;
cout << "The int var is: " << *test << endl;
Circle* c1 = new Circle(2, 2);
Rectangle* rec1 = new Rectangle(2, 2);
cout << endl;
cout << "=== Storage alloction of object ===" << endl;
cout << "The area of circle is: " << c1->getarea() << endl;
cout << "The area of rectangle is: " << rec1->getarea() << endl;
delete test;
delete c1;
delete rec1;
return 0;
}
文件流
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char data[100];
ofstream outfile;
outfile.open("test.txt");
cout << "writing to the file" << endl;
cout << "Enter your name:" << endl;
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your age: " << endl;
cin >> data;
cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("test.txt");
cout << "reading from the file:" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
return 0;
}