假设 A 类有成员“int B”和“int C”。当我创建这个类的一个对象时,我想选择它是只包含“int B”还是只包含“int C”(或者如果它同时包含它们)。
(我知道另一种方法是将 B 和 C 声明为 std::vectors 然后将它们调整为 1,但这意味着我每次使用它们时都必须在它们后面添加 [0],这也意味着我会每个成员必须浪费 20 个字节,因为 std::vector 默认使用 20B,无论您是否为其分配任何内容。)
使用继承。您可能还需要一些虚拟方法。
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()));
这是一个非常简单的工作示例:
结算.h:
#pragma once
class Settlement
{
public:
virtual void increaseMarkets()=0;
virtual int getMarketCount()=0;
};
城镇.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;
};
村庄.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;
};
简单示例.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 文件中。
这个怎么样?
首先,定义 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;