简体   繁体   中英

How can I use a value from another class in c++?

I have the main function and a class, I'am trying to use an int that is in that other class in main.

main.cpp

#include <iostream>
#include "main.hpp"

using namespace std;

int main()
{
    cout << MainInt::x << endl;
    return 0;
}

main.hpp

class MainInt
{
public:
    MainInt();
    int x;
};

MainInt::MainInt()
{
    x = 1;
}

The way I am doing it currently doesn't feel right. I feel like cout << MainInt::x << endl; is just calling the variable x.

Currently I get error: invalid use of non-static data member 'x'

What I need is to call x which is a non-static variable in MainInt such that I can output the value of x on the console. How do I go about doing that?

Either x is a static variable (also known as a global variable), and in this case, this should be:

class MainInt
{
public:
    MainInt();
    static int x;
};

// in cpp:
int MainInt::x = 1;

or it's a traditional variable, as it it feels like from the constructor. In that case, you need to instantiate an object:

MainInt variable;
cout << variable.x << endl;

Using Matthieu Brucher's solution I did the following

main.cpp

#include <iostream>
#include "main.hpp"

using namespace std;

int main()
{
    MainInt x;
    cout << x.x << endl;
    return 0;
}

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