2014-11-08 51 views
0

除了“Car”之外,还有一种方法可以根据类的不同设置每个对象的名称变量,例如“Turbo 01”或“Tank 02”或“Buggy 03”,其中id包含创建的车辆数量。不同小类的构造函数中的个性化名称

#include <iostream> 
#include <string> 
#include <sstream> 
static int id = 0; //Total Number of cars right now 
class Car 
{ 

private: 
     std::string name; 
Car() 
    { 
     std::ostringstream tmp; 
     std::string temp; 
     tmp << "Car" << ++id; 
     temp = tmp.str(); 
    } 
Car(std::string name){this->name=name; id++;} 

}; 

class Turbo : public Car() 
{ 

Turbo():Car() 
    { 

    } 
Turbo(std::string name):Car(name); 
    { 

    } 
}; 
+2

在C++中构造函数是特殊的成员函数,没有名称,并且不能被显式调用。 – 2014-11-08 17:15:06

+0

'std :: array type;'这是否实际编译? – 2014-11-08 17:21:44

+0

当您调用基础构造函数时,请将其添加为:例如Turbo(std :: string name):Car(名字,“Turbo”){..}但是std :: array不正确,数组是模板,需要实例化 – 2014-11-08 17:37:16

回答

1

首先,让我们确保class Car编译通过提供两个必需的模板参数std::array:类型和尺寸。例如:std::array<int, 10>

问题是​​需要基本类型Car的有效构造函数,然后它才能做其他任何事情。有两种方法,它的工作:

  • 要么你设计的车,所以有一个默认的consructor(i.e.without参数)
  • 或者你把构造函数汽车在涡轮增压的initialisezer名单。

为了您的编辑问题,问题是Car构造必须是派生类中可见的,所以无论是publicprotected,但不private。您也可以使用默认参数来摆脱冗余代码。

这里的解决方案:

class Car 
{ 
private: 
    static int id;  //Total Number of cars right now SO MEK IT a static class member 
    std::string name; 

public:  // public or protected so that derived classes can access it 
    Car(std::string n="Car") // if a name is provided, it will be used, otherwhise it's "Car". 
    { 
     std::ostringstream tmp; 
     std::string temp; 
     tmp << n << ++id; 
     name = tmp.str(); // !! corrected 
    } 
}; 
int Car::id = 0; // initialisation of static class member 

class Turbo : public Car 
{ 
public:         // !! corrected 
    Turbo(std::string n="Turbo") :Car(n) // !! 
    { } 
}; 
+0

你能否更新你的答案?为了解决这个问题,我做了一些改变,大约在你回答的同时。 – Curufindul 2014-11-08 17:47:50

+0

是的,我看到你已经改变了。我会努力的;-) – Christophe 2014-11-08 17:50:43

相关问题