【CPP】指針與引用的區別

https://zhuanlan.zhihu.com/p/140966943

如果標識和求址能不用同一個符號就更好理解了。


雖然指針在聲明時可以不初始化,但是在函數結束前最好為其初始化,否則就會報錯,如:

#include <algorithm> // find()
#include <fstream>
#include <iostream>
#include <iterator> // begin(), end()
#include <stack>
#include <string>
#include <vector>

using namespace std;

struct Pieces2
{
    uint64_t stick = 0;
    uint64_t hand = 0;
    uint64_t running = 0;
    uint64_t stop = 0;
    uint64_t stock = 0;
    uint64_t dead = 0;
    uint64_t free = 0;
};

struct Position2
{
	uint64_t board = 0;
    vector<Position2 *> children; // 24 Bytes
};

Position2 getValue2(string pos_start)
{
    Position2 *new_position;
	cout << "why?: ";
    new_position->board = 12;
	cout << "not?: ";
    size_t pos_find, last_pos_find, substr_len;
    vector<size_t> pos_split;
	pos_split.emplace_back(33);
    return *new_position;
}

int main()
{
    // read position
    string pos_start;
    fstream my_file("ccpos.txt");
    getline(my_file, pos_start);
    my_file.close();
    Position2 pos = getValue2(pos_start);
	cout << "3423414321432" << endl;
    return 0;
}

上面的 Position2 *new_position;要實例化: Position2 *new_position = new Position2();,否則在運行時會報錯(編譯時不報錯)。

Leave a Comment