分配与C ++中的初始化 [英] Assignment vs Initialization in C++

查看:150
本文介绍了分配与C ++中的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为构造函数控制初始化和C ++中的operator =函数控制赋值。那么为什么这个代码可以工作呢?

I thought that constructors control initialization and operator= functions control assignment in C++. So why does this code work?

#include <iostream>
#include <cmath>
using namespace std;

class Deg {
    public:
        Deg() {}
        Deg(int a) : d(a) {}        
        void operator()(double a)
        {
            cout << pow(a,d) << endl;
        }

    private:
        int d;
};

int
main(int argc, char **argv) 
{
    Deg d = 2;
    d(5);
    d = 3; /* this shouldn't work, Deg doesn't have an operator= that takes an int */
    d(5);
    return 0;
}

在main函数的第三行, $ c> int 到类 Deg 的对象。由于我没有 operator =(int)函数,我认为这肯定会失败...但是它调用 Deg int a)构造函数。那么构造函数是否也控制赋值呢?

On the third line of the main function, I am assigning an int to an object of class Deg. Since I don't have an operator=(int) function, I thought that this would certainly fail...but instead it calls the Deg(int a) constructor. So do constructors control assignment as well?

推荐答案

这就是所谓的隐式类型转换。编译器将查看是否有一个构造函数来直接从您分配的类型改变为您要分配的类型,并调用它。你可以通过在构造函数前添加显式关键字来阻止它的发生,你不希望被隐式调用,例如:

This is what's called implicit type conversion. The compiler will look to see if there's a constructor to directly change from the type you're assigning to the type you're trying to assign, and call it. You can stop it from happening by adding the explicit keyword in front of the constructor you wouldn't like to be implicitly called, like this:

explicit Deg(int a):d(a){}

这篇关于分配与C ++中的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆