简体   繁体   中英

Destructors and constructors

Would someone please explain to me why I get an "Error: not declared in this scope?"

num and denom are private members of class Rationalnumber.

Thanks!

Rationalnumber::Rationalnumber(){
num = 0;
denom = 1;
int * n = new int;
int * d = new int;
*n = num;
*d = denom;
}

Rationalnumber::~Rationalnumber(){
delete n;
}

n is a local variable in the class constructor. When it goes out of scope when the constructor completes, it is no longer visible to any other part of your application; that memory has been leaked.

There's no local or member variable called n at the point at which the destructor is called, hence: not declared in this scope.

"n" is a local variable in the constructor.

You probably want it to be a member variable in the class:

class Rationalnumber {
    int* n;
    int* d;
    .........
};
Rationalnumber::~Rationalnumber(){
delete n;
}

Is n a member of the class? If not, then it will give error, as n is neither declared in the destructor, nor is it a member of the class.

You've declared n in the constructor however, but that is local to the constructor only.The destructor (or any other function) cannot access that variable (which is declared in another function or constructor).

You define n in the scope of your constructor. This code is so simple that you shouldn't even new and delete ints. Just store n and d as class members. Your code, even fixed, would leak d as you new it but don't delete it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM