我在尝试为我的子类实现构造函数时遇到了困难。我理解构造函数的目的是将类的状态设置为传递的值?我在这是否正确?
我收到错误;
没有匹配功能可以调用超级'
我的问题是我是否必须将子类的构造函数链接到超类?两个类之间的构造函数之间的关系是什么?
#include<iostream>
using namespace std;
class Buildings
{
private:
float price, area;
string city;
public:
Buildings(float, float, string);
// Buildings(float, float, float);
void virtual display();
void virtual getprice(float);
void virtual getcity(string);
void virtual getarea(float);
};
Buildings::Buildings(float b_price, float b_area, string b_city):price(b_price), area(b_area), city(b_city)
{
}
void Buildings::display()
{
cout<<"The city, price and area(sqft) of the building are: "<<city<<endl<<price<<endl<<area;
}
void Buildings::getprice(float aprice)
{
price = aprice;//potential error handling
}
void Buildings::getarea(float asize)
{
area = asize;
}
void Buildings::getcity(string acity)
{
city = acity;
}
class Apartment:public Buildings
{
private:
float numtennants;
float rent;
float rentpr;
public:
Apartment(float numres, float numrent, float numrentpr);
void virtual display();
void virtual avgrent(float);
void virtual totrent(float);
void virtual totres(float);
};
Apartment::Apartment(float numres, float numrent, float numrentpr):numtennants(numres),rent(numrent),rentpr(numrentpr)
{}
void Apartment::display()
{
Buildings::display();
}
答案 0 :(得分:0)
您必须在子类member initializer list中调用父类的构造函数。
struct A {
A(int a) : a_(a) {}
int a_;
};
struct B : public A {
B(int a, int b) : A(a), b_(b) {}
int b_;
};
答案 1 :(得分:0)
Buildings
没有默认构造函数。您必须显式调用唯一存在的Buildings
构造函数,并传递适当的参数。
如果你想要禁止公共默认构造Buildings
对象,但允许子类使用它,你可以创建一个protected
的默认构造函数。像
class Buildings
{
public:
// Public constructor, only way to construct object of this class
// for the general public
Buildings(float, float, string);
// Other public functions...
protected:
// Default constructor, which initializes the private members
// to some suitable values
// Only usable by child-classes
Buildings()
: price(0), area(0), city("")
{}
private:
float price, area;
string city;
};