标签: conversion-operator

在C++中调用mother-class operator =的常用方法?

假设我有一个继承自Animal类的类Dog,你可能想在Dog :: operator =中插入对​​Animal :: operator =的调用.

什么是最可读/最常用的写作方式?

我想我知道那两个......

static_cast<Animal*>(this)->operator=(other);
Run Code Online (Sandbox Code Playgroud)

this->Animal::operator=(other);
Run Code Online (Sandbox Code Playgroud)

c++ inheritance operators conversion-operator

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

转换运算符正在切割我的对象

我从以下代码中获得了意外行为:

struct Base
{
    Base() {}
    virtual ~Base() {}

    virtual void foo() const = 0;

protected:
    Base(const Base &) {}
};

struct Derived : public Base
{
    Derived() {}
    Derived(const Derived &other) : Base(other) {}

    virtual void foo() const {}
};

struct NewDerived
{
    operator const Derived() { return Derived(); }
};

void func(const Base &b)
{
    b.foo();
}

int main()
{
    func(NewDerived());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用MSVC2008,我在main()中得到此编译错误:

error C2248: 'Base::Base' : cannot access protected member declared in class 'Base'
Run Code Online (Sandbox Code Playgroud)

为什么要尝试访问Base的复制构造函数? …

c++ conversion-operator object-slicing

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

是否可以使用显式模板参数调用模板化的用户定义转换运算符?

让我们考虑以下代码(使用clang ++ 7.0.0成功编译,编译器参数为-std=c++17 -Wall -Wextra -Werror -pedantic-errors):

#include <iostream>


struct Foo
{
    template <typename Type = void>
    operator int()
    {
        return 42;
    }
};


int main()
{
    const auto i = Foo{}.operator int();

    std::cout << i << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用显式提供的模板参数调用此类模板化的用户定义转换运算符?天真的方法不能编译:

const auto i = Foo{}.operator int<bool>();
Run Code Online (Sandbox Code Playgroud)

c++ templates type-conversion conversion-operator language-lawyer

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

C#如何创建一个类似于Nullable <T>的类

鉴于代码:

public class Filter<T>
{
    private bool selected = false;
    public bool Selected { get { return selected; } }

    private T value;
    public T Value { get{ return this.value; } set { this.value = value; selected = true; }
}     

public class Test
{
    public void filter()
    {
        DateTime a= new DateTime();
        Nullable<DateTime> b = new DateTime(); //Work Like a Charm
        Filter<DateTime> c = new DateTime(); //Dosent Work
    }
}
Run Code Online (Sandbox Code Playgroud)

Nullable<T>new DateTime()可直接分配到变量.在我的班上,它不起作用.我想了解我所缺少的东西.

我觉得这很简单.但我无法用言语来找到答案.

c# class type-conversion conversion-operator implicit-conversion

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

operator void*()转换仍然是C++库的一部分吗?

考虑这个程序:

#include <iostream>
int main()
{
    delete std::cout;
}
Run Code Online (Sandbox Code Playgroud)

AFAIK转换函数operator void*()const已从C++ 11中删除.因此,该程序在C++ 11编译器上的编译失败.雅,这是真的,g ++ 4.8.1和4.9.2都给出了诊断(以警告的形式,删除void*未定义,这也是好事).但是这个程序不应该在编译时失败,因为删除了转换函数,因为在C++ 98和C++ 03中,所有流对象都可以隐式转换为void*.这个错误吗?他们仍然没有实施这一改变似乎有点令人惊讶.

我在g ++ 4.9.2(支持C++ 14)中尝试过这个程序,但是它提供了警告而不是编译器错误.Ideone编译器按预期给出了错误.(在这里查看现场演示)

c++ cout g++ conversion-operator delete-operator

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