读书人

没默认的构造函数

发布时间: 2013-02-27 10:48:11 作者: rapoo

没有默认的构造函数

#include<iostream>
using namespace std;
class A
{
int x;
public:
friend class B;
A(int b)
{
x=b;
}
void Print()
{
cout<<x<<endl;
}
};
class B
{
A a;
int y;
public:
void set()
{
y=a.x;
}
void Print1()
{
cout<<"i am called "<<endl;
cout<<y<<endl;
a.Print();
}
};
int main()
{
A b=3;
b.Print();
B x;
x.set();
x.Print1();
return 0;
}

1>d:\vs2012\project\i am learning\i am learning\j.cpp(37): error C2512: “B”: 没有合适的默认构造函数可用
说我没有默认的构造函数 为什么 我之时想声明一下x啊
[解决办法]

#include<iostream>
using namespace std;
class A
{
int x;
public:
friend class B;
A(int b)
{
x=b;
}
A() // 提供一个A的默认构造就行
{
x = 0;
}
void Print()
{
cout<<x<<endl;
}
};
class B
{
A a;
int y;
public:
void set()
{
y=a.x;
}
void Print1()
{
cout<<"i am called "<<endl;
cout<<y<<endl;
a.Print();
}
};
int main()
{
A b=3;
b.Print();
B x;
x.set();
x.Print1();
return 0;
}


[解决办法]
B中有个成员A a;
你想构造个B x;
但B在构造自己时先构造成员A却不知道如何构造,因为A没有缺省的无参构造函数
要不你在B构造函数中给A成员传参,要不你给A添加一个默认无参构造

读书人网 >C++

热点推荐