我有一个Owner类,用于存储所有权信息。出于某些需要,我需要知道总共创建了多少个所有者,因此我在Owner类中创建了一个静态变量amountOfOwners。在构造函数中,我增加了amountOfOwners,在析构函数中,我减少了它。我创建了三个所有者,但在静态变量0中。
类所有者:
class Owner {
std::string fullname;
std::string inn;
std::vector<Property*> properties;
int amountOfProperty;
public:
static int amountOfOwners;
Owner(const std::string& fullname, const std::string& inn);
~Owner();
void addProperty(Property *p);
void removeProperty(const Property* p);
};
Owner::Owner(const std::string& fullname, const std::string& inn) {
this->fullname = fullname;
this->inn = inn;
amountOfProperty = 0;
amountOfOwners++;
}
Owner::~Owner() {
amountOfOwners--;
}
void Owner::addProperty(Property* p) {
properties.push_back(p);
amountOfProperty++;
}
void Owner::removeProperty(const Property* property) {
auto it = std::find(properties.begin(), properties.end(), property);
if (it != properties.end()) {
properties.erase(it);
amountOfProperty--;
}
}
}
主要:
#include <iostream>
#include "Property.h"
#include "Appartment.h"
#include "Car.h"
#include "CountryHouse.h"
#include "Owner.h"
using namespace std;
int Owner::amountOfOwners = 0;
int main()
{
std::vector<Owner> owners;
char choice;
Owner owner1("John Doe", "123456789012");
owner1.addProperty(new Appartment(100000, 80));
owner1.addProperty(new Car(50000, 200));
owner1.addProperty(new CountryHouse(200000, 50));
Owner owner2("Jane Smith", "987654321098");
owner2.addProperty(new Appartment(150000, 100));
owner2.addProperty(new Car(60000, 250));
owner2.addProperty(new CountryHouse(300000, 70));
Owner owner3("Mike Johnson", "456789012345");
owner3.addProperty(new Appartment(120000, 90));
owner3.addProperty(new Car(55000, 220));
owner3.addProperty(new CountryHouse(250000, 60));
owners.push_back(owner1);
owners.push_back(owner2);
owners.push_back(owner3);
cout << Owner::amountOfOwners;
return 0;
静态变量amountOfOwners等于0
1条答案
按热度按时间bbmckpt71#
最好使用一个单独的类来负责计算示例的数量。这是一个“单一职责原则”,并将使其他类不那么混乱的多个职责。
这里有一个例子,它跟踪了有多少个示例被创建,有多少个示例在当前处于活动状态,大多数示例在同一时间处于活动状态,以及有多少个示例被销毁。
同样的
Highwater
“mixin”可以用来跟踪尽可能多的类。