首页 > 解决方案 > 从类中返回一个字符串——奇怪的行为

问题描述

大约 10 年前,我对 C++ 编码有点兴趣,但从未真正爱上它。但是我现在的一个项目需要 c++(所以我对 c++ 有一点了解,但我不是专家)。我浏览了我的旧笔记和代码片段,让代码做我想做的事——除了一件事:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class B
{
    private:
        string ns;

    public:
        B(string ms) {ns = ms;}
        string gets() {return ns;}
};

class A
{
    private:
        vector<B> nb;

    public:
        A(vector<B> mb) {nb = mb;}
        vector<B> getb() {return nb;}
};

int main(int argc, char **argv)
{
    B b0 = B("zero");
    B b1 = B("one");
    B b2 = B("two");
    B b3 = B("three");
    A a = A({b0, b1, b2, b3});

    cout << endl << endl;

    for(auto it = a.getb().begin(); it != a.getb().end(); ++it)
        cout << it->gets() << " ";

    return 0;
}

运行此代码 (g++ -std=c++11 main.cpp) 会导致

在抛出 'std::bad_alloc'
what() 的实例后调用终止:std::bad_alloc Aborted (core dumped)

错误。这已经很奇怪了,因为这基本上只是我笔记的副本(但是,它在笔记中返回一个整数而不是字符串)。如果我改为让函数返回ns.c_str()它几乎可以工作,我得到

标签: c++stringiterator

解决方案


每个getb()ina.getb().begin()a.getb().end()返回原始向量的单独副本。将来自一个向量的迭代器与来自另一个向量的迭代器进行比较是不好的。

你可以把你的getb()方法改成这样。

const vector<B>& getb() const {return nb;}

现在begin()andend()调用将在同一个向量上工作。

或者使用更 c++11 友好的基于范围的 for 循环:

for (var b in a.getb()) {
    cout << b.gets() << " ";

哪个.begin(),.end()++适合你。

如果你绝对想使用老式的 for 循环,而不是改变你的getb()方法,你也可以这样做:

auto b_copy = a.getb();
for(auto it = b_copy.begin(); it != b_copy.end(); ++it)
    cout << it->gets() << " ";

推荐阅读