当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 类———用类定义对象———error:C++表达式必须包含类类型

类———用类定义对象———error:C++表达式必须包含类类型

2019年05月19日  | 移动技术网IT编程  | 我要评论

天天向上艾水水,纳塔莉娅·波克洛恩斯卡娅,医改最新消息

//原文参考

你以为你定义了一个类的对象,其实在编译器看来你是声明了一个函数

 1 class test{
 2 public:
 3     test(){ }//无参构造函数
 4     void fool(){ }
 5 };
 6 int main(){
 7     test t();                // 编译器会将 t 视为一个函数;
 8     t.fool();                 // 出错:c++表达式必须包含类类型
 9     return  0;
10 }

修改为:

1 //对象的定义,修改为:
2 test t;

当构造函数中存在一些参数时:

1 class test{
2 public:
3     test(int i) {}  
4     ...
5 };
6 int main(){
7     test t(5);
8     ...
9 }

当构造函数的参数带默认值:

1 class test{
2     test(int i = 0) {}
3 };
4 int main(){
5     test t;//此时i为默认值
6     test t(1);//此时i为1
7     test t();//此时报错:c++ 表达式必须包含类类型
8     ...
9 }

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网