jok*_*oon 5 c++ constructor abstract-class visual-c++
class CarPart
{
public:
CarPart(): name(""), price(0) {}
virtual int getPrice() = 0;//{return price;}
protected:
int price;
string name;
};
class Tire: public CarPart
{
public:
virtual int getPrice() {return price;}
Tire(): CarPart(), name("Tire"), price(50)
{}
};
Run Code Online (Sandbox Code Playgroud)
Visual 2010告诉我名称和价格不是衍生的成员,但它们是继承的(错误c2614).我究竟做错了什么 ?
您无法初始化不是您班级的直接成员的成员.n它不是直接的成员deriv,而是它的直接成员base.
但是,n可以访问deriv,因此您始终可以在deriv构造函数中分配它,但您应该在base构造函数中初始化它.
此外,你不能有virtual构造函数.你的意思是使用virtual析构函数吗?
class base
{
public:
base() : n(0) {} // Are you sure you don't want this?
virtual void show() = 0;
protected:
int n;
};
class deriv : public base
{
public:
deriv()
{
n = 0;
}
virtual void show() {}
};
Run Code Online (Sandbox Code Playgroud)
编辑(对OP编辑的响应):您不需要虚拟方法:
class CarPart
{
public:
CarPart(const char* newName, int newPrice) : name(newName), price(newPrice) {}
const std::string& GetName() const { return name; }
int GetPrice() const { return price; }
private:
std::string name;
int price;
};
class Tire : public CarPart
{
public:
Tire() : CarPart("Tire", 50) {}
};
Run Code Online (Sandbox Code Playgroud)
假设您CarPart的所有s都必须有名称和价格,这应该足够了.
| 归档时间: |
|
| 查看次数: |
3769 次 |
| 最近记录: |