【发布时间】:2020-07-29 18:21:51
【问题描述】:
如果我在 Visual Studio 代码或其他在线编译器上声明一个数组而没有提及它的大小,那么它可以正常工作,但如果我在 Visual Studio 中使用相同的代码,那么它就不起作用。 我知道声明未知大小的数组是不正确的,但只是由于不使用指针或任何其他东西的条件,我不得不使用它。 在 Visual Studio 上,当我只制作链接和网页类时,我就开始工作了。
谁能告诉我怎么做。
#include <iostream>
using namespace std;
class link
{
const char* name;
public:
link() :name("null")
{
cout<<"Default link constructor called"<<endl;
};
link(const char n[]) :name(n)
{
cout<< "Parameterized link constructor called"<<endl;
};
};
class webpage
{
private:
double height;
double width;
int linkno;
link links[];
public:
webpage() :height(10), width(10), linkno(2)
{
links[0]=NULL;
links[1]=NULL;
};
webpage(double hw,int lno, link hyperlinks[]) :height(hw), width(hw),linkno(lno)
{
for (int i = 0; i < linkno; i++)
{
links[i]=hyperlinks[i];
}
};
webpage(double h, double w,int lno, link hyperlinks[]) :height(h), width(w),linkno(lno)
{
for (int i = 0; i < linkno; i++)
{
links[i]=hyperlinks[i];
}
};
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;
int webpageno;
webpage wpgs[];
public:
website() :name("null"),webpageno(4)
{
wpgs[0];
wpgs[1];
wpgs[2];
wpgs[3];
};
website(const char n[],int wpn, webpage page[]) :name(n),webpageno(wpn)
{
for (int i = 0; i < webpageno; i++)
{
wpgs[i]=page[i];
}
cout<<"Parameterized website constructor called"<<endl;
};
void showdata(int linkno, int pageno)
{
cout << endl<< "Website name: " << name << endl;
for (int j = 0; j < pageno; j++)
{
cout << "Webpage #" << j + 1 << " : " << endl;
wpgs[j].showdata(linkno);
cout<<endl<<endl;
}
}
};
int main(int argc, char* argv[])
{
link link1[2]={"maha","saira"};
webpage page[1]={{32,21,2,link1}};
website site("my website",1,page);
site.showdata(2,1);
}
在 Visual Studio 上,当我只制作链接和网页类时,我就开始工作了。
【问题讨论】:
-
你不能声明一个没有大小的数组
-
尝试使用指针。
link * links = nullptr; links = new links[2048]; -
您应该详细说明为什么合适的替代方案对您不起作用。构造函数的主体(
wpgs[#];语句)也什么都不做。 -
更好的解决方案是使用
std::vector。示例:std::vector<link> links;links.push_back(hyperlinks[i]); -
这是
c的一个c++没有的功能:https://en.wikipedia.org/wiki/Flexible_array_member