简体   繁体   中英

C++ constructor and passing variables to another class

Well, just new in classes and trying to create a simple program, that has 2 classes. Class A and Class B. Well I'm trying to initialize my variable in constructor in class A, and then make some action and pass it to class B, where I'm also can make some action. So class A is a base class. However, when I compile the program I got two mistake -

error: 'i' was not declared in this scope

For class A and class B. So I have two question 1) why constructor doesn't declare variables (according to the books constructor called first)? 2) what ways I can transfer the variable from class A to use in class B?

#include <iostream>
#include <cstdio>
using namespace std;
class A {
    public:
        A(){
            int i =1;           
        }
        ~A(){}
        int foo () {
            int p = i+1;
            i++;
            return p;
        }

};

class B : public A {
    public:
        int showme() {
            return i;
        }
};

int main() {
    A j;
    B k;
    cout<< k.showme()<<endl;
    cout<< j.foo()<<endl;
return 0;
}

First off, get a good book:

The Definitive C++ Book Guide and List

and familiarize yourself with the basics. Your question indicates there is a complete mess right now in your understanding of C++.

Now on to the actual Q's.

1) C-tor does not declare a class member variable, it can only declare a local variable since a c-tor is also a function. You need to declare the member variable explicitly like so:

class A {
    int i;
public:
    A(int _i): i(_i) {  }
};

2) The term "transfer" is incorrect per se. In this case, the two classes are in an inheritance hierarchy, so the variable i is inherited by class B and if you declare it as protected , then it will be accessible in the way you do it. The function B::showme() is defined correctly. Fix the first part and the example is going to work.

3) Do not confuse classes and objects . When there is an object of class A declared, it is in no way related to another object of class A or B . j and k share their own private instances of int i (provided that you fix (a)) and if you want to have k 's instance of i to be equal to that of j , you can eg implement a copy constructor or a pair of getter/setter functions.

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