码迷,mamicode.com
首页 > 编程语言 > 详细

C++面向对象基础

时间:2017-10-14 16:51:21      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:order   return   namespace   include   指针   col   cto   ace   hello   

1. 一个小例子

main.cpp

 1 # include <iostream>
 2 # include <vector>
 3 
 4 using namespace std;
 5 
 6 # include "Object.h"
 7 
 8 int main()
 9 {
10     cout << "hello" << endl;      
11     
12     Object obj(12);
13     cout << obj.getData() << endl;
14     
15     vector<int> arr = {1,2,3};
16     //range for
17     for (auto ele : arr)
18     {
19           cout << ele << endl;    
20     }
21     return 0;                
22 }
23     

Object.h

 1 #pragma once
 2 class Object
 3 {
 4 public:
 5     //Object();//构造函数声明
 6     Object(int data);
 7     ~Object();
 8     void setData(int data);
 9     //int Object::getData();
10     int getData();
11 private:
12      int data;  
13 };    

Object.cpp

 1 #include "Object.h"
 2 Object::Object(int data)
 3 {
 4      this->data = data;  
 5 }
 6 
 7 Object::~Object()
 8 {
 9 
10 }
11 
12 void Object::setData(int data)
13 {
14      this->data = data;  
15 }
16 
17 int Object::getData()
18 {
19      return this->data;  
20 }

&

 1 void func(string str)
 2 {
 3     str = "world";
 4     cout << str << endl;    
 5 }
 6 int main()
 7 {
 8     ......
 9     string str = "hello";
10     func(str);
11     cout << str << endl;  
12 }
13 
14 print :
15 world
16 hello
17 
18 //另一种
19 void func(string& str)
20 {
21     str = "world";
22     cout << str << endl;    
23 }   
24 int main()
25 {
26     ......
27     string str = "hello";
28     func(str);
29     cout << str << endl;    
30 } 
31 
32 print:
33 world
34 world

*

 1 void func2(char filename[])
 2 {
 3    cout << filename << endl;  
 4 }
 5 
 6 int main()
 7 {
 8    char filename[] = "hello.txt"
 9    func2(filename);      
10 }
11 
12 //等价
13 void func2(char* filename)
14 {
15    cout << filename << endl;  
16 }
17 
18 int main()
19 {
20    char filename[] = "hello.txt"
21    func2(filename);      
22 }

指针

 1 void func2(char* filename)
 2 {
 3    *filename = a;
 4    cout << filename << endl;  
 5 }
 6 
 7 int main()
 8 {
 9    char filename[] = "hello.txt"
10    func2(filename);      
11 }
12 
13 print:
14 aello.txt
//*(p+offset) = p[offset]
void func2(char* filename)
{
   *(filename + 1) = a;
   cout << filename << endl;  
}

int main()
{
   char filename[] = "hello.txt"
   func2(filename);      
}

 

2. C++与python的对照

(1)

vector<int>

array

(2)

[1,2,3]  list

list<int>

(3)

(1,2,3)  set

unordered_set<int>

(4)

{1:"hello", 2:"world"}  dict

unordered_map<int, string>

 

C++面向对象基础

标签:order   return   namespace   include   指针   col   cto   ace   hello   

原文地址:http://www.cnblogs.com/Joyce-song94/p/7667439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!