ポインタ
- const char* :データ 変更不可、アドレス 変更可
- char* const :データ 変更可、アドレス 変更不可
- const char* const :データ 変更不可、アドレス 変更不可
- ポインタがさすデータのアクセスは *
アドレス代入
int num = 100 int *intptr = &num
アロー演算子
- ポインタを宣言=>newで動的確保=>アロー演算子でアクセス
- 変数からのメンバ関数呼び出し=>ドット演算子
- オブジェクトはスタック領域
- ポインタからのメンバ関数呼び出し=> アロー演算子
- オブジェクトはヒープ領域
-
#include <stdio.h> #include <iostream> class TEST { public: int figure; void calc(int temp) { figure = temp; std::cout << temp << std::endl; } }; int main() { TEST *test; // class pointer test = new TEST; //new を使用して動的確保 test->calc(10); // アロー演算子を使用して関数にアクセス std::cout << test->figure << std::endl; delete test; return 0; }
コピーコンストラクタとコピー代入演算子
使い方
A a; a(b); //コピーコンストラクタ a = b; //コピー代入演算子
違いとして、コンストラクタの方は初期化で代入演算子の方は関数の引継ぎてきな?
コピーコンストラクタ
#include <iostream> using namespace std; class A { public: A() { cout << "const A" << endl;} A(const A &obj) { cout << "copy const A" << endl; } }; int main() { A a1; A a2(a1); // OR A a2 = a1; }
代入演算子
Assignment Operators Overloading in C++
#include <iostream> using namespace std; class A { private: int feet, inches; public: A() { feet = 0; inches = 0; } A(int f, int i) { feet = f; inches = i; } void operator = (const A &obj) { feet = obj.feet; inches = obj.inches; } void display() { cout << "feet" << feet << "inches" << inches << endl; } }; int main() { A a1(11, 10); a1.display(); A a2(21, 20); a1 = a2; a1.display(); }