Domanda

I am trying to make an abstract class which allows you to call the method Fun, which is static, which prints "Abstract Class", however, it is not working, as I am using *this in a static method. I am confused on how I can reslove this problem:

class A
{
private:
    virtual void __Fun() = 0
    {
        std::cout << "Abstract Class";
    }
    static void _Fun(A &instance)
    {
        instance.__Fun();
    }
public:
    static void Fun()
    {
        _Fun(*this); // 'this' may only be used in nonstatic member functions
    }
};

int main()
{
    A a; // Throws - which is good: class is abstract
    A::Fun(); // Desired result
}
È stato utile?

Soluzione

Myabe what you want is to create not an abstract class, but a class with a private constructor (like a singleton)?

class A
{
private:
    A()
    {
    }
    virtual void __Fun()
    {
        std::cout << "Abstract Class";
    }
    static void _Fun(A &instance)
    {
        instance.__Fun();
    }
public:
    static void Fun()
    {
        A a;
        _Fun(a);
    }
};

int main()
{
    A a; // Throws - which is good: constructor is private
    A::Fun(); // Desired result
}

But then, I'm not sure why do you need such a thing at all, and why do you need virtual functions in it?

Altri suggerimenti

You may not call method __Fun such way because it requires an instance of the class but in turn you may not create an object of an abstract class. Also your class definition is invalid because pure specifier can be used only in a member function declaration. The function definition may not have the pure specifier.

To achiev what you want you could write for example

#include <iostream>

class A
{
protected:
    virtual void __Fun() = 0;
public:
    static void Fun( A &instance )
    {
        instance.__Fun(); // 'this' may only be used in nonstatic member functions
    }
};

void A::__Fun()
{
    std::cout << "Abstract Class";
}

class B : public A
{
    virtual void __Fun() { A::__Fun(); }
};


int main()
{
    B b; // Throws - which is good: class is abstract
    A::Fun( b ); // Desired result
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top