在C ++中返回对象的问题

时间:2015-04-06 03:31:11

标签: c++

我刚开始使用C ++,而且我的任务中有一部分出现问题:

class Something {
     public:
         Random& random(); // should access a data member of type Random
     private:
         Random test(int r, int c);
}

Random& Something::random() {
         return (Random&) test;
}

现在"测试"出现了错误在random()的函数定义中,因为"表达式必须是左值"我建立了解决方案,并给出了错误信息"'&' :对绑定成员函数表达式的非法操作"

我必须保持函数声明的方式,因为它在规范中以这种方式列出。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

你在评论中说:"测试"应该是一个成员变量。

然后,您需要将班级更改为:

class Something {
     public:
         Random& random(); // should access a data member of type Random
     private:

         // Not this. This declares test to be member function.
         // Random test(int r, int c);

         // Use this. This declares test to be member variable.
         Random test;
}

Random& Something::random() {
         return test;
}