首页 > 解决方案 > 如何从 C++ 中的引用类型创建指针变量?

问题描述

我想创建一个全局指针,以便所有函数都可以访问引用。

我尝试将引用地址分配给指针,但是当我尝试访问得到编译错误的值时。

vector<vector<char>>* table;

class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
        table = &board;
        cout << board[0][0] << "\n" << table[0][0];
    }
};
Line 70: Char 37: error: invalid operands to binary expression ('basic_ostream<char, std::char_traits<char>>' and '__gnu_cxx::__alloc_traits<std::allocator<std::vector<char, std::allocator<char>>>, std::vector<char, std::allocator<char>>>::value_type' (aka 'std::vector<char, std::allocator<char>>'))
        cout << board[0][0] << "\n" << table[0][0];
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^  ~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/cstddef:130:5: note: candidate function template not viable: no known conversion from 'basic_ostream<char, std::char_traits<char>>' to 'std::byte' for 1st argument
    operator<<(byte __b, _IntegerType __shift) noexcept
    ^

标签: c++c++11

解决方案


应该是(*table)[0][0]

table[0]等价于(*table)(vector 的向量board)。

table[0][x]只是board[x]。_

并且vector不可流式传输。


推荐阅读