Preliminary lecture on object oriented on March 1, 2021

Winter rain winter rain winter rain 2022-02-13 08:02:05 阅读数:202

preliminary lecture object oriented march

Code specification

using namespace std;// Represents a namespace , Indicates the space using the name ,std Standard space , It's a range 

I / O stream

int a;
double b;
cin >> a >> b;
cout << a << " " << b << endl;

Some header files

#include<string>// Can be implemented directly string Link to , Input and output 
#include<iostream>
#include<string>
using namespace std;
int main(){

string s1 = "jslkdjfl";
string s2;
cin >> s2;
string s4 = s1 + s2;
cout << s4;
return 0;
}

class

#include<iostream>
using namespace std;
class CMyTime{

private:
int h;
int m=20;
int s;
public:
void setTime(int a,int b,int c){

this->h = a;//cpp Of this It's a pointer , You need to use it to point to its members 
this->m = b;
this->s = c;
}
void showTime(){

cout << this->h << ":" << this->m << ":" <<this->s<<endl;
}
};

Be careful cpp Of private and public It's not written alone .

#include <iostream>
#include"CMyTime.cpp"// Use double quotation marks when calling under the same project 
int main(int argc, char** argv) {

CMyTime t1;
t1.setTime(7,40,30);
t1.showTime();
return 0;
}

Constructors

The constructor name is consistent with the class name , and java similar , no return value , Add parameters when creating classes , Automatically execute the constructor

Constructors must be placed in public in

Constructor is null by default , When different construction parameters are added , The program will automatically call the corresponding constructor according to the parameters stored during initialization ( heavy load )

When you add a constructor with parameters , The original parameterless constructor is overridden , If you use parameterless initialization , You need to write another parameterless constructor

#include<iostream>
using namespace std;
class CMyTime{

private:
int h;
int m=20;
int s;
public:
CMyTime(int a,int b,int c){
// Constructor with three parameters 
h = a;
m = b;
s = c ;
}
CMyTime(){
// Parameter free constructor 
}
CMyTime(int a,int b){
// Constructor for two parameters 
h = a;
m = b;
s = 0;
}
void setTime(int a,int b,int c){

this->h = a;
this->m = b;
this->s = c;
}
void showTime(){

cout << this->h << ":" << this->m << ":" <<this->s<<endl;
}
};

new Use

new Creates a new space and returns a pointer to the space

int *a = new int(6);//new One int type , The value is 6, And assign its pointer to a
int *a = new int[6];// open up 6 Size space , Notice the difference between brackets and parentheses 
copyright:author[Winter rain winter rain winter rain],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130802030971.html