具有不同类成员选择的同一类对象(C ++)

时间:2013-06-14 19:46:28

标签: c++ class oop

假设A类有成员“int B”和“int C”。当我创建这个类的对象时,我想选择它是仅包含“int B”还是仅包含“int C”(或者如果它们都包含它们)。

(我知道另一种方法是将B和C声明为std :: vectors,然后将它们调整为1,但这意味着每次使用它们时我都必须在它们之后添加[0],并且这也意味着我将不得不浪费每个成员20个字节,因为看起来std :: vector默认使用20B,无论你是否给它指定任何东西。)

2 个答案:

答案 0 :(得分:3)

使用继承。您可能也需要一些虚拟方法。

class Settlement
{
   public:
      virtual void updateMarketCount()=0;//pure virtual function
};

class Town : public Settlement
{
    public:
       virtual void updateMarketCount();
    private:
       int m_markets;
       int m_industries;
};

class Village : public Settlement
{
     public:
       virtual void updateMarketCount();
     private:
       int m_markets;
};

这样,您可以将所有这些对象分配给通用结算指针。例如:

 std::shared_ptr<Settlement> mysettlementPtr(new Town());//C++ 11 only. Found in memory header
 Settlement* mysettlementPtr = new Town();//C++ < 11

以下是如何做一个向量:

std::vector<std::shared_ptr<Settlement>> mySettlements;
mySettlements.push_back(std::shared_ptr<Town>(new Town()));
mySettlements.push_back(std::shared_ptr<Village>(new Village()));

以下是一个非常简单的工作示例:

<强> Settlement.h:

#pragma once
class Settlement
{
    public:
        virtual void increaseMarkets()=0;
        virtual int getMarketCount()=0;
};

<强> Town.h

#pragma once
#include "Settlement.h"
class Town : public Settlement
{
    public:
        Town():m_markets(0){}
        virtual void increaseMarkets(){++m_markets;}
        virtual int getMarketCount(){return m_markets;}
    private:
       int m_markets;
       int m_industries;
};

<强> Village.h

#pragma once
#include "Settlement.h"

class Village : public Settlement
{
    public:
        virtual void increaseMarkets(){++m_markets;}
        virtual int getMarketCount(){return m_markets;}
     private:
       int m_markets;
};

<强> SimpleExample.cpp:

#include<iostream>
#include<memory>
#include "Settlement.h"
#include "Village.h"
#include "Town.h"

int main()
{
    std::shared_ptr<Settlement> mysettlement(new Town());
    std::cout << "I HAVE: " << mysettlement->getMarketCount() << " MARKETS" <<  std::endl;
    mysettlement->increaseMarkets();
    std::cout << "NOW I HAVE " << mysettlement->getMarketCount() << " MARKETS" << std::endl;
    std::cout << "PRESS ENTER TO CONTINUE." << std::endl;
    system("pause");
    return 0;
}

注意:最好将功能提取到与标题相关的.cpp文件中。

答案 1 :(得分:0)

这个怎么样?

首先,定义3个包含A,B或两者的容器类。

class withA
{
  int varA;
};

class withB
{
  int varB;
};

class withAB
{
  int varA;
  int varB;
};

接下来,定义一个模板类,它是你想要的类,它包含这个成员变量,其中有A,B或A和B.

template<class T>
class theThing
{
   T m_thingMember;
};

接下来,这是你如何声明它。

theThing<withA> thingObjA;
theThing<withB> thingObjB;
theThing<withAB> thingObjAB;