与c++对象类型混淆

  • 本文关键字:类型 对象 c++ c++
  • 更新时间 :
  • 英文 :


当我试图把对象类型的数组相同的对象类型,我不知道如何把这个

Drink *a = new Drink("Whole Milk", 2.50, NEAT);
c.drinkArray[c.drinkCount++] = a;

有人能帮我吗?我来自java,所以我很困惑.....

如上所述,尽量避免使用"new"在c++中,我也倾向于避免使用"C"风格的数组(除非有明显的好处)。'C'风格的数组没有长度检查,你很容易遇到写数组越界的问题,你必须自己做一些额外的检查。

#include <string>
#include <vector>
// not really sure what NEAT is 
// but at least it can be made typesafe like this
enum class DrinkAttribute
{
UNKNWON,
NEAT,
};
struct Drink
{
std::string name = "no drink";
double price = 0.0;
DrinkAttribute attribute = DrinkAttribute::UNKNWON;
};
// put array and size information together including checks
struct Drinks
{
void add(const Drink& drink)
{
if (number_of_drinks < max_number_of_drinks)
{
drinks[number_of_drinks] = drink;
number_of_drinks++;
}
else
{
// some error handling here
}
}
Drink& get(std::size_t n)
{
if (n < number_of_drinks)
{
return drinks[n];
}
else
{
// some error handling here
// and return a drink representing no drink
// so all control paths return a value
// note I would probably just throw a std::invalid_argument exception here
// but I consider exception handling to be out of the scope of the question.
return no_drink;
}
}
static const std::size_t max_number_of_drinks = 10;
Drink drinks[max_number_of_drinks];
Drink no_drink;
std::size_t number_of_drinks = 0;
};
void ShowDrinksWithVector()
{
// to make dynamic collections of something you're bettor of using std::vector
// instead of arrays. This way you reuse tested code!
std::vector<Drink> drinks;
// at a drink to the collection of drinks
// the 3 arguments passed to emplace_back are used
// to construct an object of type Drink
drinks.emplace_back("Whole Milk", 2.50, DrinkAttribute::NEAT);
}
void ShowDrinksWithArray()
{
// this way you will have to write memory access checking code yourself
// that's why you will end up with an extra class (or you have to resort
// to using global variables)

Drinks drinks;
drinks.add(Drink{ "Whole Milk", 2.50, DrinkAttribute::NEAT });
auto drink = drinks.get(0);
}
int main()
{
ShowDrinksWithVector();
ShowDrinksWithArray();
}

最新更新