Frage

Alright, I just thought give C++ a try (I currently do C#), now my first problem is class instantiating or calling a method in another class.

Here is my code: My main Program entry:

#include <iostream>
#include "myClass.h"
using namespace std;
    int main()
    {
        myClass* mc = new myClass();
    }

The Class I'm trying to access:

#include "myClass.h"
myClass::myClass()
{
    void DoSomething();
    {

    }
}
myClass::~myClass()
{
}

The Class Header:

#pragma once
class myClass
{
public:
    myClass();
    ~myClass();
};

Now as you can see i have instantiated the class, but i cant access DoSomething() method.

War es hilfreich?

Lösung

This code simply declares a local function, and has an empty scope for fun:

myClass::myClass()
{
    void DoSomething(); // local function declaration

    {
      // empty scope    
    }
}

If you want doSomething() to be a member of myclass, you have to declare it in the class definition:

class myClass
{
public:
    myClass();
    ~myClass();
    void doSomething();
};

then implement it

void myclass::doSomething() { .... }

Also note that you don't have to use new everywhere in C++. You can instantiate an object like this:

int main()
{
    myClass mc;
}

Also note that using namespace std; isn't such a great idea anyway, at least not in real code.

Andere Tipps

this is a function declaration in a constructor (+an ampty scope within { }).

myClass::myClass()
{
    void DoSomething();
    {

    }
}

You want a function declaration in class body (not in constructor) and definition of this function (this can be done immediately together with declaration or later as i.e. here):

class myClass
{
public:
    myClass();
    ~myClass();
    void doSomething();
};

implementation of constructor:

myClass::myClass() { .... }

implementation of your function, similarly:

void myClass::doSomething() { .... }

The method you are trying to use in main must be part of the class definition. You can write an inline function or can have a separate definition of that function. Also, you need to make that function public in order to access it from main.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top