Code
#include <iostream>
using namespace std;
class C {
int one, two;
public:
C(int x, int y) : one(x), two(y) {}
int sum(void) { return one + two; }
};
int main()
{
int a = 1, b = 2;
int *pa = &a;
int *pb = &b;
cout << "simple int pointer : ";
cout << "a + b = " << (*pa + *pb) << endl;
C c(3,4);
cout << "[C c ] is same as [int a ] [Type t] : ";
cout << "c.sum() = " << c.sum() << endl;
C *pc;
pc = &c;
cout << "pc->sum() equals to (*pc).sum() : " << endl;
cout << "pc->sum() = " << pc->sum() << endl;
cout << "(*pc).sum() = " << (*pc).sum() << endl;
C *pc_n;
pc_n = new C (5,6);
cout << "pc_n = new C( 5, 6) : " << endl;
cout << "pc_n->sum() = " << pc_n->sum() << endl;
pc = nullptr;
delete pc;
delete pc_n;
return 0;
}
Run
simple int pointer : a + b = 3
[C c ] is same as [int a ] [Type t] : c.sum() = 7
pc->sum() equals to (*pc).sum() :
pc->sum() = 7
(*pc).sum() = 7
pc_n = new C( 5, 6) :
pc_n->sum() = 11
Note
构造函数
C(int x, int y) : one(x), two(y) {}
- class C的构造函数,接受两个整型的参量
对象创建
C c(3,4);
- 创建一个class C的对象c,接受整数3以及整数4作为构造函数的参数
方法调用
cout << "c.sum() = " << c.sum() << endl;
Screen Output : c.sum() = 7
- 很自然地就可以使用
c.sum()
调用类中的函数
类指针
C *pc;
pc = &c; // C c(3,4);
- 创建一个类的指针 取名为pc 本质就是
Type *t
,Class 也是一种Type,那么自然可以对c
进行取出地址的操作&
,并将其值赋予pc
cout << "pc->sum() = " << pc->sum() << endl;
cout << "(*pc).sum() = " << (*pc).sum() << endl;
Screen Output:
pc->sum() = 7
(*pc).sum() = 7
pc->sum()
以及(*pc).sum()
是两种等价的写法
new的用法
C *pc_n;
pc_n = new C (5,6);
pc_n
仍旧是一个类指针,但是被赋值为new C (5,6)
Java vs C++
// java code
C c = new C(5,6);
// java code
// C++ code
C c(5,6);
or
C *pc;
pc = new C(5,6);
or
C *pc;
C c;
pc = &c;
// C++ code
java
和C++
的写法做一下区分记忆
Reference
[1] classes/Pointers to classes
http://www.cplusplus.com/doc/tutorial/classes/
[2] Comparison of Java and C++
https://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B