gpt4 book ai didi

c++ - 一参数构造函数和赋值运算符

转载 作者:行者123 更新时间:2023-11-30 02:44:21 26 4
gpt4 key购买 nike

考虑以下代码:

#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++ 标准,ISO/IEC 14882:2011(E),编程语言 C++。

下面的代码

A obj1 = 2;

是一个初始化。它在第 8.5 节初始化器的第 16 节中进行了描述。

16 The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. If the initializer is not a single (possibly parenthesized) expression, the source type is not defined.

此条款的以下部分很长。我只引用与您的示例代码相关的部分。

— If the destination type is a (possibly cv-qualified) class type:

— If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload esolution is ambiguous, the initialization is ill-formed.

第 13.3.1.3 节是构造函数的初始化。

根据8.5和13.3.1.3,构造函数

A(int);

被选中初始化obj1。


至于第二个

obj1 = 3;

此行为由 5.17 赋值和复合赋值运算符第 4 节定义。

4 If the left operand is of class type, the class shall be complete. Assignment to objects of a class is defined by the copy/move assignment operator (12.8, 13.5.3).

13.5.3 分配,第 1 条。

1 An assignment operator shall be implemented by a non-static member function with exactly one parameter. Because a copy assignment operator operator= is implicitly declared for a class if not declared by the user (12.8), a base class assignment operator is always hidden by the copy assignment operator of the derived class.

函数

void operator =(int);

被选中

obj1 = 3;

根据重载规则。

关于c++ - 一参数构造函数和赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25360835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com