【发布时间】:2017-09-27 00:20:07
【问题描述】:
{} 运算符不是赋值运算符吗?另外,为什么int val{10};在main里面工作,但是构造函数下面的赋值是非法的?
查看示例
此代码有效:
class Time{
int _H, _M, _S;
public:
Time(int h = 0, int m = 0, int s = 0){_H={h};
_M={m};
_S={s};};
~Time(){}
};
这不是:
class Time{
int _H, _M, _S;
public:
Time(int h = 0, int m = 0, int s = 0){_H{h}; //here is the difference
_M{m};
_S{s};};
~Time(){}
};
我从 GCC 收到的消息是这个
classes.cpp: In constructor ‘Time::Time(int, int, int)’:
classes.cpp:48:44: error: expression cannot be used as a function
Time(int h = 0, int m = 0, int s = 0){_H{h};
^
classes.cpp:49:16: error: expected ‘;’ before ‘{’ token
_M{m};
^
classes.cpp:50:16: error: expected ‘;’ before ‘{’ token
_S{s};};
^
【问题讨论】:
-
不要使用以下划线后大写字母开头的标识符!这些是为实现(编译器和标准库)保留的。
标签: c++ constructor operators assign