我是 Cpp 的新手,我只是想構建一個非常基本的“Circle”類。下面是我的代碼
#include <iostream>
#include <cmath>
#include <typeinfo>
class Circle {
private:
const double pi = 3.14159265358979323846;
double radius;
double area;
double perimeter;
public:
void set_rad(double rad){
radius = rad;
area = pi*pow(rad,2);
perimeter = 2*pi*rad;
}
double get_attr() {
double circle_attr[3] = {radius, area, perimeter};
std::cout << typeid(circle_attr).name() << std::endl;
return *circle_attr;
}
};
int main(){
Circle aCircle;
aCircle.set_rad(5);
aCircle.get_attr();
return 0;
}
代碼運行并按預期運行。但是,如果在方法的回傳行中get_attr替換*circle_attr為circle_attr,則會出現錯誤cannot convert 'double*' to 'double' in return。然而,circle_attr已經是一個雙打陣列。這就是我初始化它的原因,也是 Cpp 告訴我的,因為當我打電話給typeid(circle_attr).name()我時,我會回傳A3_d,我認為它是 Array3_double 的縮寫。那么這里發生了什么?
uj5u.com熱心網友回復:
您遇到的實際問題是嘗試從函式回傳 C 陣列。這不是一件可以做到的事情。如果需要,最小的可能更改是將您的函式更改為如下所示:
#include <array>
// [...]
std::array<double, 3> get_attr() {
std::array<double, 3> circle_attr{radius, area, perimeter};
std::cout << typeid(circle_attr).name() << std::endl;
return circle_attr;
}
你說你的函式應該回傳一個雙精度,然后你嘗試回傳一個雙精度陣列,或者在你的情況下實際上只是半徑。
std::array 不過有點亂,因為大小是型別資訊的一部分。
這是您的代碼,進行了一些調整以使其更符合 C 并完全重寫您的get_attr()函式。
#include <cmath>
#include <iostream>
#include <tuple> // CHANGED: Needed for structured binding usage in get_attr()
class Circle {
private:
const double pi = 3.14159265358979323846;
double radius = 0.0; // CHANGED: Kept the default member initialization going
double area = 0.0;
double perimeter = 0.0;
public:
Circle() = default; // CHANGED: Added constructors
Circle(double r)
: radius(r), area(pi * std::pow(radius, 2)), perimeter(2 * pi * radius) {}
void set_rad(double rad) {
radius = rad;
area = pi * pow(rad, 2);
perimeter = 2 * pi * rad;
}
// CHANGED: Using C 17 feature called structured bindings; also made function
// const, since it shouldn't alter the data
auto get_attr() const { return std::make_tuple(radius, area, perimeter); }
};
int main() {
Circle aCircle(5.0); // CHANGED: Now we can use constructors
// aCircle.get_attr(); // NOTE: Didn't even try to save info anywhere
auto [radius, area, perimeter] = aCircle.get_attr();
std::cout << "Radius: " << radius << "\nArea: " << area
<< "\nPerimieter: " << perimeter << '\n';
return 0;
}
輸出:
Radius: 5
Area: 78.5398
Perimieter: 31.4159
我們添加了建構式,這是 C OOP 的基本部分。您可以看到main()建構式如何允許我們在宣告站點進行初始化。
I also left one your original lines in main() to note that even if get_attr() worked, you didn't save the info at all. So you wouldn't have had it anyway.
Your get_attr() function has been written to take advantage of a C 17 feature called structured bindings. It also takes advantage of another feature called CTAD, just to keep the one line in get_attr() succinct.
In order for you to test this, you'll need to add the -std=c 17 flag to the compile command you're using. It's good practice to always specify the standard version you're using.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/315001.html
