这是我使用合成的代码。我删除了不相关的功能,以使其更易于理解。当我使用参数化的构造函数运行此代码时,它可以正常工作。但是,如果我在初始化它时使用默认构造函数不起作用,则代码将在两者之间终止。
#include <iostream>
using namespace std;
class link
{
const char* name;
public:
link() :name("null")
{};
link(const char n[]) :name(n)
{};
~link()
{
cout << "destructor called " << endl;
};
};
class webpage
{
private:
double height;
double width;
link* links;
public:
webpage() :height(10), width(10),links(new link[1])
{};
webpage(double hw, link* hyperlinks) :height(hw), width(hw), links(hyperlinks)
{ };
webpage(double h, double w, link* hyperlinks) :height(h), width(w), links(hyperlinks)
{ };
~webpage()
{
delete [] links;
cout << "page destructor called " << endl;
};
void showdata(int linkno)
{
cout << "height: " << height << endl;
cout << "width: " << width << endl;
cout << "links " << endl;
for (int i = 0; i < linkno; i++)
{
cout << "link #" << i + 1 << " = " << links[i].getname() << endl;
}
}
};
class website
{
private:
const char* name;
webpage* wpgs;
public:
website() :name("null"),wpgs(new webpage[1])
{};
website(const char n[], webpage* page) :name(n), wpgs(page)
{};
~website()
{
delete[] wpgs;
cout << "website destructor " << endl;
};
void showdata(int linkno, int pageno)
{
cout << "Website name: " << name << endl;
for (int j = 0; j < pageno; j++)
{
cout << "Webpage #" << j + 1 << " : " << endl;
wpgs[j].showdata(linkno);
}
}
};
int main(int argc, char* argv[])
{
link* link1=new link[2] {{"maha"},{"saira"}};
link* link2=new link[3] {{"areeb"},{"aima"},{"umair"}};
link* link3=new link[2] {{"ahmad"},{"azra"}};
link* link4=new link[4] {{"usama"},{"tyabba"},{"ali"},{"hamza"}};
webpage* page=new webpage[4] {{2,link1},{3.2,5.2,link2},{4,1,link3},{42,13,link4}};
website site("my website",page);
site.showdata(2,4);
}
上面的代码工作正常,但是如果我使用下面的代码中的默认构造函数
int main()
{
link* links;
webpage* page;
website site("website", page);
site.showdata(1, 1);
}
现在它将无法正常工作。带有终止代码。并生成错误error1'links':使用未引用的局部变量
error2未初始化的局部变量'page'
如何使用默认的构造函数来简化操作,请帮忙。有问题的实施的所有条件都是问题陈述的要求。
您没有使用任何构造函数,因为links
和page
是指针。指针没有构造函数。
也许你想要这个?
webpage page;
website site("website", &page);
现在,因为page
不是指针,所以webpage
将调用默认构造函数。
或查看其余的代码,可能这是正确的。
webpage* page = new webpage[1];
website site("website", page);
new webpage[1]
调用网页的默认构造函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句