Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
我想直接访问作为类成员的向量BigArray::v并将其打印出来。但是编译器不会构建我的代码:

#include <iostream>
#include <vector>
using namespace std;

class BigArray
{
private:

    vector<int> v={1,2,3,4,5,6,7,8,9,10};
    int accessCounter;
public:
    const vector<int> & getVector() const {return v;}
};


int main(int argc, const char * argv[]) {
    // insert code here...
    BigArray b;
    cout<< *b.getVector()<< endl;
    return 0;
}

最佳答案

有两个问题:


b.getVector()返回对向量的引用,因此使用*b.getVector()会尝试取消引用引用,这是无效的。您可能打算只使用b.getVector()而不是*b.getVector()
将向量流式传输到std::ostream之类的std::cout没有过载。您必须编写自己的示例,例如:




#include <iostream>
#include <vector>
using namespace std;

class BigArray {
private: /* Fields: */
    vector<int> v={1,2,3,4,5,6,7,8,9,10};
    int accessCounter;
public: /* Methods: */
    const vector<int> & getVector() const {return v;}
};

template <typename T>
std::ostream & operator<<(std::ostream & os, std::vector<T> const & v) {
     bool first = true;
     os << '{';
     for (auto const & elem : v) {
         if (!first) {
             os << ", ";
         } else {
             first = false;
         }
         os << elem;
     }
     return os << '}';
}

int main(int argc, const char * argv[]) {
    // insert code here...
    BigArray b;
    cout<< b.getVector() << endl;
    return 0;
}

10-01 17:02