gpt4 book ai didi

c++ - 内置类型的运算符函数

转载 作者:行者123 更新时间:2023-11-28 01:32:47 26 4
gpt4 key购买 nike

如何为内置类型定义的运算符显式使用底层运算符函数?看代码:

struct Int
{
Int() = default;
Int(int initial)
{
i = initial;
}

Int operator+(Int other)
{
return Int(i + other.i);
}

int i;
};

std::ostream& operator<< (std::ostream &out, const Int& data)
{
out << data.i;
return out;
}

int main()
{
Int a, b = 5, c = 5;
a = b + c;

std::cout << a << std::endl;

Int d, e = 5, f = 5;
d.operator=(e.operator+(f)); // possible with user defined types

std::cout << d << std::endl;

int g, h = 5, j = 5;
g.operator=(h.operator+(j)); // illegal

return 0;
}

标有“非法”的部分产生以下错误:

request for member 'operator+' in 'h', which is of non-class type 'int'

我知道你不能在非类类型的 int 上调用方法。问题是 operator+ 的含义在哪里定义以及是否可以显式使用它。

最佳答案

How can I explicitly use the underlying operator functions for operators defined for built-in types?

你不能。

如果您正在寻找标准的相关部分,那么它应该是:

16.5 Overloaded operators

6 An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

关于c++ - 内置类型的运算符函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50782807/

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