简体   繁体   English

我可以将对象分配给整数变量吗?

[英]Can I assign a object to a integer variable?

Let say I have a object. 假设我有一个对象。 I'm assigning that to an integer. 我将其分配给一个整数。

MyClass obj1 = 100;//Not valid

Let's say, I have a parameterized constructor which accepts an integer. 假设,我有一个接受整数的参数化构造函数。

MyClass(int Num)
{
    // .. do whatever..
}

MyClass obj1 = 100;//Now, its valid

Likewise on any circumstance, does the vice-versa becomes valid?!. 同样在任何情况下,反之亦然有效吗?!

eg) int Number = obj1;//Is it VALID or can be made valid by some tweeks

EDIT : 编辑

I found this to be possible using Conversion Functions. 我发现使用转换功能可以做到这一点 Conversion functions are often called "cast operators" because they (along with constructors) are the functions called when a cast is used. 转换函数通常称为“ cast运算符”,因为它们(以及构造函数)是使用强制转换时调用的函数。

Conversion functions use the following syntax: 转换函数使用以下语法:

operator conversion-type-name () 运算符转换类型名称()

eg) Many have explained it neatly below 例如)许多人在下面对其进行了巧妙的解释

Yes, provided that the object is implicitly convertible to an int , either directly or through an intermediate object. 是的,前提是该对象可以直接或通过中间对象隐式转换为int

Eg If your class have a conversion operator int it would work: 例如,如果您的类具有转换operator int则它将起作用:

MyClass
{
public:
    operator int() const { return 200; }
};

C++ constructors that have just one parameter automatically perform implicit type conversion. 仅具有一个参数的C ++构造函数会自动执行隐式类型转换。 This is why conversion from int to MyClass works. 这就是为什么从int转换为MyClass的原因。 To create conversion from MyClass to int you have to define operator int() inside MyClass. 要创建从MyClass到int的转换,必须在MyClass内定义operator int()

Yes you can, using user defined conversions. 是的,可以使用用户定义的转换。

In your MyClass, define operator int() 在您的MyClass中,定义运算符int()

So 所以

class MyClass
{
 int myVal;

public:
operator int() { return myVal;}

}

Yes, you need to add a conversion operator to MyClass 是的,您需要向MyClass添加转换运算符

operator int(); 运算符int();

MyClass is not an integer therefore you can't do int Number = obj1; MyClass不是整数,因此您不能做int Number = obj1; You should have a method or operator(stated by others) in MyClass that returns an int. 您应该在MyClass中有一个返回int的方法或运算符(由他人声明)。 ( int number = obj1.GetNum(); ) int number = obj1.GetNum();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM