我正在撰寫一些示例代碼,希望能抓住我目前的掙扎。假設我有一個用于一些一般形狀的類Shape
和一個很好的函式,它可以將任何形狀的周長加倍
float DoublePerimeter (shared_ptr<Shape> shape)
return 2*shape->GetPerimeter();
};
是否可以在類本身中使用這樣的功能?
class Square : Shape {
float side = 1;
public:
void Square(float aside) : side(aside) {;}
float GetPerimeter(){return 4*side;}
void Computation() { DoublePerimeter (??????);}
};
我可以通過什么來??????完成這項作業?我嘗試使用類似的東西
shared_ptr<Shape> share_this(this);
并且還嘗試enable_shared_from_this<>了我的課程,但是我傳遞給函式的指標總是在鎖定時回傳 null。這甚至可能嗎,或者這是一個糟糕的設計?我是否被迫將此函式設為成員函式?
uj5u.com熱心網友回復:
如果您不想使用enable_shared_from_this,可能是因為您的物件并不總是由共享指標擁有,您總是可以通過使用無操作洗掉器來解決它:
void nodelete(void*) {}
void Square::Computation() { DoublePerimeter({this, nodelete}); }
但這是一種技巧(而且相當昂貴,因為您分配和釋放控制塊只是為了控制您正在呼叫的函式)。
一種更簡潔的解決方案,盡管可能需要更多的輸入,是將您的自由函式實作與所有權方案分開:
float DoublePerimeter(Shape const& shape)
return 2*shape.GetPerimeter();
};
float DoublePerimeter(std::shared_ptr<Shape> shape)
return DoublePerimeter(*shape);
};
void Square::Computation() const { DoublePerimeter(*this); }
uj5u.com熱心網友回復:
我已經試過了。它似乎對我有用。請參見此處或下方。我修復了一些小問題,并讓 Computation 回傳一個值以用于演示目的。
#include <memory>
#include <cassert>
#include <iostream>
class Shape {
public:
virtual float GetPerimeter(){return 0;}
};
float DoublePerimeter (std::shared_ptr<Shape> shape){
return 2*shape->GetPerimeter();
}
class Square : public Shape, public std::enable_shared_from_this<Square> {
float side = 1;
public:
Square(float aside) : side(aside) {}
float GetPerimeter(){return 4*side;}
float Computation() {
return DoublePerimeter (this->shared_from_this());
}
};
int main(){
auto square = std::make_shared<Square>(3.0);
std::cout <<square->Computation() << std::endl;
return 0;
}
編輯:
@pptaszni 評論的示例。將主要更改為:
int main(){
Square square{3.0};
std::cout << (&square)->Computation() << std::endl;
return 0;
}
將導致運行時錯誤:
Program returned: 139
terminate called after throwing an instance of 'std::bad_weak_ptr'
what(): bad_weak_ptr
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513367.html
標籤:C c 11
