类 class
class 和 struct很相似 都是自己定义一个类型 类型里可以包涵很多类型。 区别是class增加了访问修饰符 public 和 private
class object {
public:
int a;
int b;
private:
double c;
double d;
};
public
public 是可以被全程序访问的。 例如变量a和b。
private
private 只能被class里的函数访问。
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
class object {
public:
int x;
int y;
void Test(object* that) {
cout << that->x<<" "<<that->y<< endl;
Test2(); //不可以再main函数里直接调用test2 但是可以用test来间接调用test2
}
private:
void Test2() {
printf("I am a private function!\n");
}
double c;
double d;
};
int main() {
object obj;
obj.x = 10;
obj.y = 20;
obj.Test(&obj);
object* p=&obj;
p->x = 20;// p是一个指针 所有我们可以用->来调用obj里的x p已经指向了obj
p->y = 10;// 调用对象的时候把指针传给他
p->Test(p);
return 0;
}
this 指针
调用this的实质就是一个定义的class 加*的类型。
比如我们用了obj.Test() 那么Test里的this 其实指向的就是 obj
void Test() { //用了this 这里就不需要再传递指针了
cout << this->x<<" "<<this->y<< endl;
}
举例
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
class object {
public:
int x;
int y;
void Test() { //用了this 这里就不需要再传递指针了
cout << this->x<<" "<<this->y<< endl;
}
int add() {
return this->x + this->y;
}
private:
void Test2() {
printf("I am a private function!\n");
}
double c;
double d;
};
int main() {
object obj;
obj.x = 10;
obj.y = 20;
obj.Test();
object* p=&obj;
p->x = 20;// p是一个指针 所有我们可以用->来调用obj里的x p已经指向了obj
p->y = 10;// 调用对象的时候把指针传给他
p->Test();
cout<<p->add()<<endl;
object obj1;
obj1.x = 6;
obj1.y = 6;
cout << obj1.add();
return 0;
}
输出:
10 20
20 10
30
12
如何控制再private里的变量
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
class object {
public:
void set(int a, int b) {
this->x = a;
this->y = b;
}
void Test() { //用了this 这里就不需要再传递指针了
cout << this->x<<" "<<this->y<< endl;
}
int add() {
return this->x + this->y;
}
private:
int x;// 现在我们把x 和y 写道 private里来 这样再main中我们就不可以修改x和y的值了
int y;// 解决方法就是我们可以写一个新的函数再 public里 这样我们就可以用过public里的函数来控制private的值了
void Test2() {
printf("I am a private function!\n");
}
double c;
double d;
};
int main() {
object obj;
//obj.x = 10;
//obj.y = 20;
obj.set(10, 20);
obj.Test();
object* p=&obj;
//p->x = 20;// p是一个指针 所有我们可以用->来调用obj里的x p已经指向了obj
//p->y = 10;// 调用对象的时候把指针传给他
p->set(20, 10);
p->Test();
cout<<p->add()<<endl;
object obj1;
obj1.set(6, 6);
cout << obj1.add();
return 0;
}
输出:
10 20
20 10
30
12
下面来看一下我们创建的这些p obj和obj1 在内存里是什么样的
我们在main函数最下面添加几行code
cout << "&obj:" << &obj << endl;
cout << "p:" << p << endl;
cout << "&obj1" << &obj1 << endl;
输出:
&obj:00BBFC70
p:00BBFC70
&obj100BBFC44