我有这个代码:
#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) class Obj
{
private:
Obj& self{*this};
// now use self for . notation and this for -> notation
public:
}
Run Code Online (Sandbox Code Playgroud)
这种用法是否有任何缺点,或者将“self”作为在类中使用的选项只是一个坏主意?
#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)