C++ 中的赋值与初始化

发布于 2024-08-21 22:25:56 字数 713 浏览 3 评论 0原文

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

#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 函数的第三行,我将一个 int 分配给 Deg 类的对象。由于我没有 operator=(int) 函数,我认为这肯定会失败......但它调用了 Deg(int a) 构造函数。那么构造函数也控制赋值吗?

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;
}

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白馒头 2024-08-28 22:25:56

这就是所谓的隐式类型转换。编译器将查看是否有一个构造函数可以直接从您分配的类型更改为您尝试分配的类型,并调用它。您可以通过在您不希望隐式调用的构造函数前面添加 explicit 关键字来阻止这种情况发生,如下所示:

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

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) {}

糖果控 2024-08-28 22:25:56

只是为了澄清 JonM 的答案:

对于 d = 3 行,涉及赋值运算符。正如 JonM 所说,3 被隐式转换为 Deg,然后该 Deg分配d 使用编译器生成的赋值运算符(默认情况下执行按成员赋值)。如果你想阻止赋值,你必须声明一个私有赋值运算符(并且不实现它):

//...
private:
    Deg& operator=(const Deg&);
}

Just to clarify JonM's answer:

For the line d = 3, an assignment operator is involved. 3 is being implicitly converted to a Deg, as JonM said, and then that Deg is assigned to d using the compiler-generated assignment operator (which by default does a member-wise assignment). If you want to prevent assignment, you must declare a private assignment operator (and do not implement it):

//...
private:
    Deg& operator=(const Deg&);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文