【发布时间】:2014-09-15 15:52:06
【问题描述】:
考虑以下代码:
#include <iostream>
using namespace std;
class A{
private:
int a;
public:
A(int);
void print();
void operator =(int);
};
// One argument constructor
A::A(int b){
cout<<"Inside one argument constructor"<<endl;
this->a=b;
}
void A:: operator =(int b){
cout<<"Inside operator function"<<endl;
this->a = b;
}
void A::print(){
cout<<"Value of a ="<<a<<endl;
}
int main() {
/* INITIALIZATION */
A obj1=2;
obj1.print();
/* ASSIGNMENT */
obj1=3;
obj1.print();
return 0;
}
上面代码的输出可以在这里看到:http://ideone.com/0hnZUb。它是:
Inside one argument constructor
Value of a =2
Inside operator function
Value of a =3
所以我观察到的是,在初始化期间,调用了单参数构造函数,但在赋值期间,调用了重载的赋值运算符函数。这种行为是由 C++ 标准强制执行的,还是特定于编译器的?任何人都可以引用标准中定义此行为的部分吗?
【问题讨论】:
-
这是标准行为,你期待什么?
-
您观察到在构造过程中调用了构造函数,在赋值过程中调用了赋值运算符。
-
请记住,符号在声明中具有不同的含义;该声明中的
=不是运算符,它是指定初始化程序的语法的一部分。
标签: c++