使用默认构造函数初始化对象 [英] Initialization of object with default constructor
本文介绍了使用默认构造函数初始化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
创建对象与()或无
有这样的代码:
class MojaKlasa{
public:
MojaKlasa(){}
MojaKlasa(int i){}
void fun(){}
};
int main()
{
MojaKlasa a;
a.fun();
MojaKlasa b(1);
b.fun();
MojaKlasa c(); // initialize with default constructor
//c.fun(); error: request for member ‘fun’ in ‘c’, which is of non-class type ‘MojaKlasa()’
return 0;
}
- 为什么对象c有错误?
- 使它工作的方式是什么?
- 真正的意思是MojaKlasa c() - 它是函数声明吗?
推荐答案
MojaKlasa c();
这会声明一个名为 c
code> MojaKlasa ,它不是一个对象声明。如果你想声明一个局部对象,你需要省略括号。这只是一个语言规则,编译器必须将此形式解释为一个函数声明。
This declares a function called c
returning MojaKlasa
, it's not an object declaration. If you want to declare a local object you need to omit the parentheses. It's just a language rule that the compiler has to interpret this form as a function declaration.
MojaKlasa c;
这篇关于使用默认构造函数初始化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文