【发布时间】:2011-06-13 14:38:44
【问题描述】:
class phone {
public:
phone(int x) { num = x; }
int number(void) { return num; }
void number(int x) { num = x; }
private:
int num;
};
int main(void)
{
phone p1(10);
p1 = 20; // here!
return 0;
}
大家好
只是我声明了一个像上面这样的简单类。
之后,我将 int 值分配给该类的对象,然后它就起作用了!
(我打印了它的值。它被正确存储了)
如果没有带 int 参数的构造,则发生编译错误。
所以,我认为它与构造函数有关。对吗?
请给我一个很好的解释。
谢谢。
【问题讨论】:
-
在 C++ 中,如果没有参数,最好不要放置 void。你也可以让你的号码获得一个 const 函数。
标签: c++ constructor variable-assignment assignment-operator