C++ 类初探
2015-07-17 06:44
381 查看
感悟:
C++:无非是C 的语法特性 与 C++的类语法相结合,支持面向对象和面向过程的混合。
当然,C++的 STL 库,以及包括容器等内容,是扩充的,需要慢慢来熟悉。
代码:
过程感想:
1. C++ 的类,无非就是在C的基础上,封装成了 Java 中类的变体。(当然,语言特性不一样,语法区别很大)
2. 和Java 类的初始化相比,不需要 new,直接 S(10) 就够了。(但是不确定,有堆地址分配的情况,没有尝试)
3. C++ 中的 this 与java中的不一样(是const的,我猜想它是类属性,而非对象的属性)。
gcc编译过程中,报错:
hello.cpp:(.text+0xd1):
undefined reference to `std::cout'
hello.o: In function `__static_initialization_and_destruction_0(int,
int)':
hello.cpp:(.text+0x19e):
undefined reference to `std::ios_base::Init::Init()'
hello.cpp:(.text+0x1a3):
undefined reference to `std::ios_base::Init::~Init()'
后参照文章:http://www.cnblogs.com/chinazhangjie/archive/2011/05/23/2054598.html
用 g++ 编译,问题解决。
C++:无非是C 的语法特性 与 C++的类语法相结合,支持面向对象和面向过程的混合。
当然,C++的 STL 库,以及包括容器等内容,是扩充的,需要慢慢来熟悉。
代码:
#include<iostream> #include<stdlib.h> using namespace std; struct ListNode { int val; struct ListNode * next; }; class Solution { public: struct ListNode * sortList(struct ListNode * head) { cout << "x = " << head->val << endl; } Solution(int X) { x = X; } int getX() { cout << x << endl; } private: int x; }; int main() { Solution S(10); struct ListNode* M; M = (struct ListNode *)malloc(sizeof(struct ListNode)); M->val = 100; M->next = NULL; S.sortList(M); S.getX(); return 0; }
过程感想:
1. C++ 的类,无非就是在C的基础上,封装成了 Java 中类的变体。(当然,语言特性不一样,语法区别很大)
2. 和Java 类的初始化相比,不需要 new,直接 S(10) 就够了。(但是不确定,有堆地址分配的情况,没有尝试)
3. C++ 中的 this 与java中的不一样(是const的,我猜想它是类属性,而非对象的属性)。
gcc编译过程中,报错:
hello.cpp:(.text+0xd1):
undefined reference to `std::cout'
hello.o: In function `__static_initialization_and_destruction_0(int,
int)':
hello.cpp:(.text+0x19e):
undefined reference to `std::ios_base::Init::Init()'
hello.cpp:(.text+0x1a3):
undefined reference to `std::ios_base::Init::~Init()'
后参照文章:http://www.cnblogs.com/chinazhangjie/archive/2011/05/23/2054598.html
用 g++ 编译,问题解决。
相关文章推荐