基于方法重载类

问题描述 投票:1回答:1

我想用某种方法用不同的方法多次声明同一个类:

class A // Implementation 1
{
    void someMethod();
};

class A // Implementation 2
{
    void someMethod();
    void anotherMethod();
};

class A // Implementation 3
{
    void entirelyDifferentMethod();
};

基本概念是根据使用的方法选择合适的A类。主要用途是,我可以实现一个具有不同数据结构的类,这些数据结构依赖于实际调用的方法。

有没有办法在C ++中实现它,以便以下工作?

A class1;

class1.someMethod(); // class1 is using implementation 1 of class A

A class2;

class2.someMethod();
class2.anotherMethod(); // class2 is using implementation 2 of class A

A class3;

class3.entirelyDifferentMethod(); // class3 is using implementation 3 of class A
c++ class overloading
1个回答
0
投票

模板专业化可能有所帮助。我不确定你的目标是什么,但试试这个:

template<int N>
class A;

template<>
class A<1>
{
public:
     void f(){std::cout<<"A1 f()"<<std::endl;}
};

template<>
class A<2>
{
public:
     void f(){std::cout<<"A2 f()"<<std::endl;}
     void g(){std::cout<<"A2 g()"<<std::endl;}
};



int main()
{
     A<1> a;
     A<2> b;

     a.f();
     b.f();
     b.g();
}

输出是:

A1 f();
A2 f();
A2 g();

仅供参考:编译器无法从对象名称中推断出对象类型。

© www.soinside.com 2019 - 2024. All rights reserved.