C++复制构造函数参数问题

今天遇到一个题,
#include <iostream>
using namespace std;
class Sample {
public:
int v;
// 在此处补充你的代码
};
void PrintAndDouble(Sample o)
{
cout << o.v;
cout << endl;
}
int main()
{
Sample a(5);
Sample b = a;
PrintAndDouble(b);
Sample c = 20;
PrintAndDouble(c);
Sample d;
d = a;
cout << d.v;
return 0;
}
——题目来自郭炜老师的mooc。
该题十分简单,不非是构造函数以及复制构造函数的问题,十来分钟就编完了,并且在VS中运行成功通过了,输出了正确答案,但是却遇到一个十分奇怪的问题,也就是在DEV_C++里始终无法通过,一直报错,困扰我许久,后经同学们的提醒告知,终于修改成功,得到正确的代码。

#include <iostream>
using namespace std;
class Sample {
public:
    int v;
    // your code

    // this is default constructor func
    Sample (){}

    //constructor func
    Sample(int n)
    {
        v = n;
    }

    //copy_constructor func
    Sample(const Sample & x){
        v = x.v + 2;
    }


};
void PrintAndDouble(Sample o)
{
    cout << o.v;
    cout << endl;
}
int main()
{
    Sample a(5);          // this will cause the constructor func
    Sample b = a;        //one class is used to initiate anither class, so constructor func will be used
    PrintAndDouble(b);
    Sample c = 20;       
    PrintAndDouble(c);
    Sample d;         //this will use the default constructor func
    d = a;
    cout << d.v;
    return 0;
}

刚开始犯的错误是在复制构造函数
//copy_constructor func
Sample(const Sample & x){
v = x.v + 2;
}

中参数写成了Sample & x,也就是没有用常引用,真是哭笑不得。
在《新标准c++程序设计》中写道复制构造函数只有一个参数,参数类型是本类的引用。复制构造函数的参数可以是const引用,也可以是非const引用。一般使用前者,这样既能以常量对象作为参数,也可以以非常量对象作为参数去初始化其他对象。而在本题中应该就是一个常量对象作为参数——20。
我原先的理解是Sample c = 20; 等价于Sample c (20);,但是从该题来看似乎并不是这样,因为后者是可以成功编译通过的,而前者不行,Sample c = 20是通过
Sample(const Sample & x){
v = x.v + 2;
}
来初始化的。而不是Sample(int n)来初始化的。而20应该就是被当做是一个const类型的量了。
不过对于此我还是有一些疑问的:
1、为什么原来Sample & x作为参数在vs中可以编译通过,并输出正确答案,但是dev——c++中却不行。
2、Sample c = 20;究竟是如何初始化的其实心里还是一知半解。
3、如果我之前的理解是对的,Sample c = 20;中的20为何会被当做const型呢?

如果有高手知道,还请留言告知,之后我如果明白了,也会来做修改。

猜你喜欢

转载自blog.csdn.net/qq_39805362/article/details/82737110