如何在C++中初始化嵌套类的构造函数
问题描述:
我在初始化嵌套类构造函数时遇到问题。如何在C++中初始化嵌套类的构造函数
这里是我的代码:
#include <iostream>
using namespace std;
class a
{
public:
class b
{
public:
b(char str[45])
{
cout<<str;
}
}title;
}document;
int main()
{
document.title("Hello World"); //Error in this line
return 0;
}
我得到的错误是:
fun.cpp:21:30: error: no match for call to '(a::b)'
答
你必须要么使你的数据成员的指针,或者你只能调用数据成员的构造从它是成员类的顾问的初始化列表(在这种情况下,a
)
答
您可能想要类似于:
class a
{
public:
a():title(b("")) {}
//....
};
这是因为title
已经是a
一员,但你不必为它的默认构造函数。可以编写一个默认构造函数或将其初始化为初始化列表。
答
此:
document.title("Hello World");
不是 “初始化嵌套类”;它试图在对象上调用operator()
。
当您创建document
时,嵌套对象已经初始化。除此之外,因为你没有提供默认的构造函数。
答
那么你在这里:
class A {
B title;
}
没有定义构造函数A类(如图所示Luchian格里戈里)标题将被初始化为:B title();
您可以工作,围绕由:
A::A():title(B("Hello world"))
// Or by adding non parametric constructor:
class B {
B(){
}
B(const char *str){
}
}
对象标题(在文档中)已经初始化,您不能再调用构造函数,但仍可以使用语法:document.title(...)
通过声明并确定operator()
,但它不会是构造了:
class B {
const B& operator()(const char *str){
cout << str;
return *this;
}
}
什么是错误讯息? – 2012-02-06 12:43:13
@OliCharlesworth fun.cpp:21:30:错误:不匹配呼叫'(a :: b)' – sandbox 2012-02-06 12:46:49