在c ++中,获取函数没有返回值

时间:2018-03-05 03:51:32

标签: c++ return

我在另一个类中使用来自一个类的对象成员时遇到问题,而在main中调用的GetColor()函数没有打印任何问题。它应该打印出B.的颜色属性。我的问题在哪里?我的代码:

#include <iostream>
#include <vector>

using namespace std;

class B{
private:
    string color;
    int id;
    int val;
public:
    B(){}
    B(int newid, string newcolor){
        cout<<"constructor"<<endl;
        id = newid;
        color = newcolor;
    }
    B(const B & b){
        color = b.color;
        id = b.id;
        val = b.val;
    }

    string GetColor(){return color;}
    void SetVal(int newval){val = newval;}
};

C类,包含对象成员B:

class C{
private:
    B b;
    int num;
public:
    C(int newnum) {num = newnum;}
    void SetB(B newb){
        b = newb;
        b.SetVal(-1);
    }

    B GetB(){return b;}
};

W类,包含对象C:

的向量
class W{
private:
    vector <C> c;
public:
    W(){
        for (int i = 0; i < 5; i++){
            c.push_back(C(i));
        }
    }
    C CAt(int i){
        return c.at(i);
    }
};

int main(){
W w;
w.CAt(0).SetB(B(1, "red"));
cout << w.CAt(0).GetB().GetColor()<<endl;
return 0;
}

输出为“构造函数”,后跟空白换行符,打印的颜色为空字符串。

0 个答案:

没有答案