我有這段代碼,但是我沒有看到我在這裏出錯的地方。它似乎編譯好,但我不能訪問Computer
或Appliance
函數。有人可以幫助我瞭解如何在這個代碼示例中創建一個擁有不同對象的數組?創建不同對象的數組
#include <iostream>
using namespace std;
class Technics
{
private:
int price, warranty;
static int objCount;
double pvn;
char *name, *manufacturer;
public:
Technics()
{
this->objCount++;
};
Technics(int price)
{
this->objCount++;
this->price = price;
}
~Technics(){
this->objCount = this->objCount - 2;
};
static int getObjCount()
{
return objCount;
}
void setPrice(int price)
{
this->price = price;
}
int getPrice()
{
return this->price;
}
void resetCount()
{
this->objCount = 0;
}
};
int Technics::objCount = 0;
class Computer : public Technics
{
private:
int cpu, ram, psu, hdd;
public:
Computer() {}
Computer(int price)
{
this->setPrice(price);
}
void setCpu(int cpu)
{
this->cpu = cpu;
}
int getCpu()
{
return this->cpu;
}
};
class Appliance : public Technics
{
private:
int height;
int width;
char* color;
char* type;
public:
Appliance(){}
Appliance(int height, int width)
{
this->height = height;
this->width = width;
}
void setWidth(int width)
{
this->width = width;
}
int getWidth()
{
return this->width;
}
};
void main()
{
//Creating array
Technics *_t[100];
// Adding some objects
_t[0] = new Computer();
_t[1] = new Computer();
_t[2] = new Appliance();
// I can access only properties of Technics, not Computer or Appliance
_t[0]->
int x;
cin >> x;
}
可能最好拿起一本關於C++的好書,並圍繞着繼承和多態的概念。順便說一下,不存在「一組不同的對象」:所有的數組元素都是相同的類型,即'Technics *'。 –
好吧,有一個陣列boost :: variant <...>,boost :: any或void *當然......(在不斷上升的程度上) – sehe
當然你只能訪問Technics的屬性,因爲它是一個指針到'技術'。另外'Technics * _t [100]'是一個指向'Technics'數組的指針。這不是你想要的。請使用'std :: vector' –