C++物件導向基礎

來源:互聯網
上載者:User

標籤: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 for17     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 world16 hello17 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 world34 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++物件導向基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.