如何在 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:错误:与调用“(a::b)”不匹配
I am getting problems in initializing the nested class constructor.
Here is my code:
#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;
}
The error I get is:
fun.cpp:21:30: error: no match for call to '(a::b)'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想要类似的内容:
这是因为
title
已经是a
的成员,但是您没有它的默认构造函数。要么编写一个默认构造函数,要么在初始化列表中对其进行初始化。You probably want something like:
This is because
title
is already a member ofa
, however you don't have a default constructor for it. Either write a default constructor or initialize it in the initialization list.您必须使数据成员成为指针,或者只能从其所属类的构造函数的初始化列表中调用数据成员的构造函数(在本例中为
a
)You have to either make your data member a pointer, or you can only call the data member's constructor from the initialiser list of the construtor of the class it is a member of (in this case,
a
)这:
不是“初始化嵌套类”;它尝试在对象上调用
operator()
。当您创建
文档
时,嵌套对象已经初始化。但事实并非如此,因为您没有提供默认构造函数。This:
is not "initializing the nested class"; it's attempting to call
operator()
on the object.The nested object is already initialised when you create
document
. Except that it's not, because you've provided no default constructor.那么这里有什么:
如果没有为 A 类定义构造函数(如 Luchian Grigore 所示),标题将被初始化为:
B title();
您可以通过以下方式解决这个问题:
对象标题(在文档中)已经初始化,您不能再调用构造函数,但您仍然可以通过声明和定义
operator()
使用语法:document.title(...)
但它不会'不再是构造函数:So what do you have here:
Without defining constructor for class A (as Luchian Grigore shown) title will be initialized as:
B title();
You can work that around by:
Object title (in document) is already initialized and you cannot call constructor anymore, but you still may use syntax:
document.title(...)
by declaring and definingoperator()
but it won't be constructor anymore: