标签: explicit-conversion

C++多个运算符=()

我正在写一个String类.我希望能够分配我的字符串,如;

a = "foo";
printf(a);
a = "123";
printf(a);
int n = a; // notice str -> int conversion
a = 456; // notice int -> str conversion
printf(a);
Run Code Online (Sandbox Code Playgroud)

我已经为string到整数转换分配了operator =()方法.如何声明另一个operator =()以便我可以执行反向方法?

当我宣布另一个时,它似乎覆盖了前一个.

String::operator const char *() {
    return cpStringBuffer;
}
String::operator const int() {
    return atoi(cpStringBuffer);
}
void String::operator=(const char* s) {
    ResizeBuffer(strlen(s));
    strcpy(cpStringBuffer, s);
}
bool String::operator==(const char* s) {
    return (strcmp(cpStringBuffer, s) != 0);
}

//void String::operator=(int n) {
//  char _cBuffer[33];
//  char* s = itoa(n, …
Run Code Online (Sandbox Code Playgroud)

c++ operators conversion-operator implicit-conversion explicit-conversion

3
推荐指数
1
解决办法
1848
查看次数

如何使用显式转换运算符将一个列表转换为另一个列表而不使用扩展方法?

我将此转换运算符添加到我的类中并且运行良好。当我传递一个类的对象时A,它会将其转换为类的对象B

public static explicit operator B(A a)
{
    //Convert A to B
}
Run Code Online (Sandbox Code Playgroud)

但是当我想将 a 转换List<A>为 a时List<B>,它不起作用。我尝试了以下代码,但它也不起作用。

public static explicit operator List<B>(List<A> a)
{
    //Convert List<A> to List<B>
}
Run Code Online (Sandbox Code Playgroud)

相反,它会抛出以下编译器错误:

用户定义的转换必须与封闭类型相互转换。

我不想使用扩展方法来转换它。

c# conversion-operator explicit-conversion

3
推荐指数
1
解决办法
5794
查看次数

为什么不对转换构造函数进行隐式转换?

所以我有这个代码:

struct Foo {
    Foo() { cout << "default\n"; }
    Foo(const long long) { cout << "implicit\n"; }
};

struct Bar {
    Bar(const short param) : param(param) {}
    operator long long() const { return static_cast<long long>(param); }
    const short param;
};
Run Code Online (Sandbox Code Playgroud)

我本以为Foo foo = Bar(13)会使用我的隐式转换然后转换构造函数.但它错误:

错误:从请求转换Bar为非标量类型Foo

这工作正常:Foo foo(Bar(13)).为什么我的隐式转换用于显式转换构造,而不用于隐式转换构造?

我从https://en.cppreference.com/w/cpp/language/copy_initialization获得的规则说:

转换的结果,如果使用转换构造函数,则是prvalue表达式,然后用于直接初始化对象

c++ constructor implicit-conversion typecast-operator explicit-conversion

3
推荐指数
1
解决办法
75
查看次数

在 cpp 中为 double 和 string 数据类型定义运算符 +

我正在尝试使用以下函数为字符串和双定义运算符 +

string operator + (const double& b,const string a){
    return to_string(b)+a;
}
Run Code Online (Sandbox Code Playgroud)

当我进行以下操作时,效果很好

double c = 100.256;
string d = "if only";
cout<<c+d<<"\n";
Run Code Online (Sandbox Code Playgroud)

但是当我传递 const char 而不是 string 时,它会抛出编译错误('double'和'const char [4]'类型的无效操作数到二进制'operator+')

double c = 100.256;
string test = c+"sff";
Run Code Online (Sandbox Code Playgroud)

为什么不发生 const char[] "sff" 到字符串的隐式转换?

c++ operator-overloading operator-keyword explicit-conversion

3
推荐指数
1
解决办法
144
查看次数

隐式/显式转换运算符未被属性调用(System.ComponentModel.DataAnnotation.dll)

我们在域模型中使用了自定义LocalizedString类型.我们想用验证属性来装饰属性MaxLength.为此,我们添加了隐式运算符以启用此属性所需的强制转换.

奇怪的是,运算符似乎永远不会被调用,并且在属性IsValid方法中抛出了InvalidCastException .在我们自己的项目中执行此演员表.

在这个系统clr ngen'ed属性中有没有特殊的强制转换行为编译器magix?

// Custom type
public class LocalizedString
{
    public string Value
    {
        get { return string.Empty; }
    }

    public static implicit operator Array(LocalizedString localizedString)
    {
        if (localizedString.Value == null)
        {
            return new char[0];
        }

        return localizedString.Value.ToCharArray();
    }
}

// Type: System.ComponentModel.DataAnnotations.MaxLengthAttribute
// Assembly: System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ComponentModel.DataAnnotations.dll
public override bool IsValid(object value)
{
  this.EnsureLegalLengths();
  if (value == null)
  {
    return true;
  }
  else
  {
    string str = value …
Run Code Online (Sandbox Code Playgroud)

c# implicit-conversion data-annotations explicit-conversion

2
推荐指数
1
解决办法
1210
查看次数

为什么C#在完全知道它没有结构类型时会取笑?

我很惊讶今天看到这是可能的,但我担心这必须在之前讨论过.

public interface ICanAdd
{
    int Add(int x, int y);
}

// Note that MyAdder does NOT implement ICanAdd, 
// but it does define an Add method like the one in ICanAdd:
public class MyAdder
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

public class Program
{
    void Main()
    {
        var myAdder = new MyAdder();
        var iCanAdd = (ICanAdd)myAdder; //compiles, but for what sake?
        int sum = iCanAdd.Add(2, 2); //na, not game for it, …
Run Code Online (Sandbox Code Playgroud)

c# casting interface structural-typing explicit-conversion

2
推荐指数
1
解决办法
272
查看次数

在类外定义显式运算符bool()时出错

operator bool()在课外定义函数有问题

class A{

public:
    explicit operator bool() const; 
};
Run Code Online (Sandbox Code Playgroud)

我在课外定义函数为......

explicit A::operator bool() const {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误 - error: ‘explicit’ outside class declaration

做错了什么?

c++ explicit explicit-conversion c++11

2
推荐指数
1
解决办法
1056
查看次数

为什么通用列表的显式转换不起作用

我试图在consturctor中为一个派生类IntersectionPath转换一个对象列表,如下所示.

    public class IntersectionPath : Path<IntersectionSegment>, IEnumerable
    {          

        //Constructors
        public IntersectionPath() : base() {  Verts = null; }

        public IntersectionPath(List<Intersection> inVerts, List<Segment<Node>> inEdges) : base() 
        {
            this.Segments = (List<IntersectionSegment>) inEdges;
        }

    }
Run Code Online (Sandbox Code Playgroud)

段在通用基类Path中定义

    public class Path<T> : IEnumerable<T> where T : Segment<Node>
    {   
        //public properties
        public List<Direction> Directions {get; set; }
        public List<T> Segments  {  get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我已经为IntersectionSegment类中的强制转换定义了一个显式运算符(见下文,因此不清楚为什么这不会编译.我在IntersectionPath构造函数中有一个错误消息.

public class IntersectionSegment : Segment<Intersection>
{           
    //curves which intersect the primary curve at I0(Start Node) and I1(End Node)
    public Curve …
Run Code Online (Sandbox Code Playgroud)

c# generics casting explicit-conversion

1
推荐指数
2
解决办法
2562
查看次数

带有指针的C++显式构造函数

我最近偶然发现了一个接收单个指针参数的显式构造函数.我想知道在这种情况下是否需要显式关键字?因为没有指针的构造函数所以不能有任何隐式转换.

class Foo {
 public:
  explicit Foo(int* int_ptr);
}
Run Code Online (Sandbox Code Playgroud)

c++ instantiation explicit-conversion

1
推荐指数
1
解决办法
252
查看次数

C#中继承的奇怪行为

我对C#很新,所以我希望如果我的问题听起来很愚蠢请原谅我的无知.

-我尝试Inheritance用丰达C#,发现它在一些奇怪的行为方式,所以我想用检查出来Java,我得到了我的预期的结果.

-我只是想知道这里有什么我想念的.......

C#代码:

 class Animal
 {
   public void Sound()
   {
     System.Console.WriteLine("I don't make any sound");
   }


 } 





 class Dog : Animal
 {
   public void Sound()
   {
     System.Console.WriteLine("barking");


   }  

 }


 class InheritTest
 {
   static void Main()
   {
     Animal a = new Dog();         // Implicit conversion

     Dog    d = (Dog) a;   // Explicit conversion


     a.Sound();
     d.Sound();

   }

 }
Run Code Online (Sandbox Code Playgroud)

输出:

I don't make any sound
barking
Run Code Online (Sandbox Code Playgroud)

JAVA代码:

 class Animal
 {
   public void sound()
   { …
Run Code Online (Sandbox Code Playgroud)

c# java inheritance implicit-conversion explicit-conversion

0
推荐指数
1
解决办法
83
查看次数

在java中显式转换时,short 128 = byte -128如何?

import java.util.Scanner;

public class ShortToByte{
  public static void main (String args[]){
    int i=0;
    while (i<6){
      Scanner sinput = new Scanner (System.in);
      short a = sinput.nextShort();
      byte b = (byte) a;
      System.out.println("Short value : " + a + ",Byte value : " + b);
      i++;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我试图理解不同数据类型之间的转换,但我很困惑 128 = -128 字节的短值如何以及短值 1000 = -24 字节的值如何?

我一直在使用以下逻辑将 Short 转换为 byte :

十进制 1000 -> 二进制 = 0000 0011 1110 1000

转换为字节时: xxxx xxxx 1110 1000 相当于: 232

我确实注意到正确的答案是二进制值的二进制补码,但是什么时候我们使用二进制补码进行转换,什么时候不使用二进制补码将 3450 从短转换为字节时我没有使用二进制补码但达到了预期的结果。 …

java byte short type-conversion explicit-conversion

0
推荐指数
1
解决办法
648
查看次数

为什么非 const 引用不能初始化为不同类型的对象?

我正在阅读这本书,它写道我们可以将一种类型的常量引用分配给任何其他类型的对象,原因是,内部编译器将Rvalue分配给与引用相同类型的对象,然后const引用被初始化为相同类型的对象,但是,如果这种类型的隐式转换有助于将常量引用分配给不同类型的对象,那么为什么不能隐式地进行相同的转换,因为对于这种显式转换。

#include<iostream>
using namespace std;
int main()
{
    int a = 10;

    double temp = (double)a;
    double &x = temp;
    cout << x << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它的工作方式相同,为什么它没有在编译器中预先配置?

c++ reference implicit-conversion explicit-conversion

0
推荐指数
1
解决办法
83
查看次数