小编Sai*_*000的帖子

递归虚拟调用不能正常工作?

我有这个代码:

#include <iostream>
#include <string>
using namespace std;

struct Flower
{
    virtual string str() = 0;
};

struct Rose : Flower
{
    string str() override { return "A rose"; }
};

struct RedFlower : Flower
{
    Flower& flower;
    RedFlower(Flower& flower) : flower{ flower } {}
    string str() override { return flower.str() + " that is red"; }
};

int main()
{
    Rose rose;
    RedFlower red_rose{ rose };
    RedFlower red_red_rose{ red_rose };
    RedFlower red_red_red_rose{ red_red_rose };
    cout << rose.str() << endl; …
Run Code Online (Sandbox Code Playgroud)

c++ recursion

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

在课堂上使用 this 是否安全?

class Obj
{
private:
    Obj& self{*this};
    // now use self for . notation and this for -> notation
public:
}
Run Code Online (Sandbox Code Playgroud)

这种用法是否有任何缺点,或者将“self”作为在类中使用的选项只是一个坏主意?

c++ visual-c++

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

为什么这个右值引用仅适用于整数而不适用于结构

#include <iostream>

//option 1
struct Obj
{
    auto f(int&& x) { printf("&&\n"); }
    auto f(int const& x) { printf("const&\n"); }
    
    auto g() const { return int{}; } 
    const auto h() const { return int{}; } 
};

//option 2
struct Obj2
{
    auto f(Obj&& x) { printf("&&\n"); }
    auto f(Obj const& x) { printf("const&\n"); }

    auto g() const { return Obj{}; } 
    const auto h() const { return Obj{}; } 
};

int main()
{
    {
        int x;
        Obj obj;
        obj.f(obj.g()); // …
Run Code Online (Sandbox Code Playgroud)

c++

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

标签 统计

c++ ×3

recursion ×1

visual-c++ ×1