1

Recently I have to use C++ for a course at university. I'm aware of the concept of pointers and references, but i'm humbling at a specific point.

consider following class definition:

class test{
    public:
        test(int i);
        ~test();
        int* getint();
    private:
        int *asdf;
};

test::test(int i){
     asdf = new int();
    *asdf = i;
}

int* test::getint(){
    return asdf;
}

and the following code:

void fun1(int*& i){
    *i +=1;
}

int main(){
    test *a = new test(1);
    fun1(a->getint());
}

If i'm compiling it with g++ i'll get an error message:

error: invalid initialization of non-const reference of type ‘int*&’ from an rvalue of type ‘int*’

I see where the problem is, and that it can be solved by declaring a new pointer like this:

int main(){
    test *a = new test(1);
    int* b = a->getint();
    fun1(b);
}

But is there any other way to use the return value directly as a reference? If my C++ code is terrible, you're welcome to correct it (it's basicly my first week of C++).

EDIT: changed fun1 to use reference and corrected initilization of class variable (as suggested by enrico.bacis

4

2 回答 2

3

您正在asdf隐藏实例变量的类测试的构造函数中定义一个新变量。

换行:

int* asdf = new int();

和:

asdf = new int();
于 2012-10-31T17:57:20.750 回答
1

有几个问题,如在 C++ 中,您必须正确管理内存,并且不能一直调用 new 而不处理以后的删除。

我认为这

void fun1(int* i)
{
  *i +=1;
} 

会给 +=1 比 * 更高的运算符优先级,所以你需要这样做:

void fun1(int* i)
{
  (*i) +=1;
} 

请注意,该函数需要int*作为参数 not int *&int *&如果您想修改指针本身,而不是它指向的内容,您只会采用。在这种情况下,您无法传递getint()似乎给您编译器错误的返回值。

于 2012-10-31T18:00:39.897 回答